fgetcsv / str_getcsv无法正确解析fputcsv的输出

时间:2016-01-19 08:41:55

标签: php csv

我不知道这是我的错误还是PHP的错误?我有这段代码:

<?php

if (!function_exists('str_putcsv')) {
    function str_putcsv($input, $delimiter = ',', $enclosure = '"', $escape = '\\') {
        $fp = fopen('php://temp', 'r+b');
        fputcsv($fp, $input, $delimiter, $enclosure, $escape);
        rewind($fp);
        $data = rtrim(stream_get_contents($fp), "\n");
        fclose($fp);
        return $data;
    }
}

$a[] = 'Bro the';
$a[] = "Bro\nther";
$a[] = 'Bro"ther';
$a[] = 'Bro""ther';
$a[] = 'Bro\ther';
$a[] = '12345678';
$a[] = '12345678\\';
$a[] = 'Bro ther';
$a[] = '12345678\\\\';
$a[] = '"12345678"';

print $x1 = print_r($a, 1);


$s=str_putcsv($a,';','"','\\');


print_r($s);
print "\n";

$a=str_getcsv($s,";",'"','\\');
print $x2 = print_r($a ,1);

print 'same? ' . ($x1==$x2);
print "\n";

代码输出:

Array
(
    [0] => Bro the
    [1] => Bro
ther
    [2] => Bro"ther
    [3] => Bro""ther
    [4] => Bro\ther
    [5] => 12345678
    [6] => 12345678\
    [7] => Bro ther
    [8] => 12345678\\
    [9] => "12345678"
)
"Bro the";"Bro
ther";"Bro""ther";"Bro""""ther";"Bro\ther";12345678;"12345678\";"Bro ther";"12345678\\";"""12345678"""
Array
(
    [0] => Bro the
    [1] => Bro
ther
    [2] => Bro"ther
    [3] => Bro""ther
    [4] => Bro\ther
    [5] => 12345678
    [6] => 12345678\";Bro ther"
    [7] => 12345678\\
    [8] => "12345678"
)
same? 

fgetcsv的结果数组与源数组不同,后者应该相同。我做错了吗? 另一个问题:

  1. 为什么fputcsv不会逃避“到\”并且不要逃避\到\\
  2. 为什么fgetcsv / str_getcsv不要将\\替换为\
  3. 我正在使用PHP 5.6.4-4ubuntu6.4

    由于

0 个答案:

没有答案