[英]PHP: I'm getting strange output from CSV file with double quotes like \x00P\x00h\x00o\x00n
I am using a simple function to upload a .csv file and turn it into an associative array. 我正在使用一个简单的函数上传.csv文件,并将其转换为关联数组。 It works fine without quotes around it but I am getting really strange output if there are quotes.
它在没有引号的情况下可以正常工作,但是如果有引号,我会得到非常奇怪的输出。
My working file looks like this: 我的工作文件如下所示:
Phone number:
+1 5556666999
+1 5551123336
And here is my output: 这是我的输出:
array:2 [▼
0 => array:1 [▼
"Phone number" => "+1 5556666999"
]
1 => array:1 [▼
"Phone number" => "+1 5551123336"
]
]
print_r(csvToAssocArray($filename);
function csvToAssocArray($filename)
{
$csvAsArray = array_map(function($d) {
return str_getcsv($d, ",");
}, file($filename));
$header = array_shift($csvAsArray);
$csv = array();
foreach ($csvAsArray as $row) {
$csv[] = array_combine($header, $row);
}
return $csv;
}
But if I have a file like this with double quotes around my values then I get this value. 但是,如果我有一个像这样的文件,在我的值周围用双引号引起来,那么我就得到了这个值。
My file: 我的档案:
"Phone number"
"+1 55500718"
"+1 55551919"
file_get_contents($file)
"""
"\x00P\x00h\x00o\x00n\x00e\x00 \x00n\x00u\x00m\x00b\x00e\x00r\x00"\x00\n
\x00"\x00+\x001\x00 \x005\x005\x005\x000\x000\x007\x001\x008\x00"\x00\n
\x00"\x00+\x001\x00 \x005\x005\x005\x005\x001\x009\x001\x009\x00"\x00\n
\x00
"""
print_r(csvToAssocArray($filename);
array:3 [▼
0 => array:1 [▼
"\x00P\x00h\x00o\x00n\x00e\x00 \x00n\x00u\x00m\x00b\x00e\x00r\x00\x00" => "\x00"\x00+\x001\x00 \x005\x005\x005\x000\x000\x007\x001\x008\x00"\x00"
]
1 => array:1 [▼
"\x00P\x00h\x00o\x00n\x00e\x00 \x00n\x00u\x00m\x00b\x00e\x00r\x00\x00" => "\x00"\x00+\x001\x00 \x005\x005\x005\x005\x001\x009\x001\x009\x00"\x00"
]
2 => array:1 [▼
"\x00P\x00h\x00o\x00n\x00e\x00 \x00n\x00u\x00m\x00b\x00e\x00r\x00\x00" => "\x00"
]
]
What is happening here? 这是怎么回事 Even file_get_contents gives strange output.
甚至file_get_contents也会给出奇怪的输出。
Your file is probably encoded in UTF-16 (probably incorrectly called "Unicode" in wherever you're exporting this from), which means every other byte is a NUL
byte for basic ASCII characters. 您的文件可能采用UTF-16编码(无论从何处导出,都可能错误地称为“ Unicode”),这意味着每个其他字节都是基本ASCII字符的
NUL
字节。 You'll either want to convert the file to plain ASCII/UTF-8 outside of PHP, or convert it inside of PHP with iconv
or mb_convert_encoding
. 您可能想要在PHP外部将文件转换为纯ASCII / UTF-8,或者在PHP内部使用
iconv
或mb_convert_encoding
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.