我希望能够读取一个csv文件,使用PHP base64_decode()对其进行解码,然后将该解码后的数据以相同格式写入新文件中。
我尝试逐行读取文件,然后在读取文件时对其进行解码,但数据不断损坏或损坏(包含符号和随机字符)。
我的csv文件只有一列base64编码的字符串,没有定界符。每个字符串在其自己的行上,每行只有一个字符串。
像这样:
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
ZXhhbXBsZUBlbWFpbC5jb20=
etc...
我希望我的新文件具有相同的格式和相同的数据,但应该对其进行解码。
像这样:
example@email.com
example@email.com
example@email.com
example@email.com
etc...
这就是我读取数据的方式。我尝试在base64_decode中使用trim()来消除任何可能的空格或字符,但这没有帮助。我还没有写到csv部分,因为我需要适当的输出。
// csv file is uploaded via a form, I move it to the uploads/ directory
$csv_file = $_FILES['file']['name'];
// filename will always be the user uploaded file
$file_name = $csv_file;
// open the file in read
if (($handle = fopen("uploads/".$file_name, "r")) !== FALSE) {
// read the file line by line
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
// display column of data
echo base64_decode($data[0]);
}
// close file
fclose($handle);
}
我的预期输出:
example@email.com
example@email.com
example@email.com
example@email.com
etc...
我的实际输出:
�XZ�˘��A͡����չ兡��������X\�\�[�\�PXZ�˘��\�\��YM�XZ�˘��G7FWfV�g&GF������6��email@example.com�]�[�ܙ[�XZ�˘��G6ӓ���#T�����6��#7C7##4�����6��ɽ���Ѽ��������兡��������ٜ̌LPXZ�˘��Aɕ�����������email@examplevV�W'6��CCT�����6��v�G7W���d�����6��v���v��&W$�����6��ݥ�����齝兡������wwwemail@exampleemail@exampleۙ�\�MLMP[����]]��NNۚ�XZ�˘��Aщɽݸ������兡������[٘[M�[����Aѡ������͕�٥���
�������ѡ����ѽ�������������[YX���ܝ
答案 0 :(得分:0)
让它正常工作……只是需要自动检测行尾。
// without this my code breaks, I'm assuming since my csv has no delimiter it was having issues finding the line endings
ini_set('auto_detect_line_endings', TRUE);
// Store each row in this array
$allRowsAsArray = array();
// open file
if (!$fp=fopen("uploads/".$csv_file,"r")) echo "The file could not be opened.<br/>";
// add each row from col into array
while (( $data = fgetcsv ( $fp , 0)) !== FALSE )
{
$allRowsAsArray[] = $data;
}
// decode array line by line, also add linebreaks back in
foreach($allRowsAsArray as $result) {
echo base64_decode($result[0])."\n";
}
答案 1 :(得分:0)
<?php
$file = new SplFileObject("data.csv");
while (!$file->eof()) {
echo base64_decode($file->fgetcsv());
}