Liga
Liga

Reputation: 3439

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. 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.

Upvotes: 0

Views: 829

Answers (1)

deceze
deceze

Reputation: 522250

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. 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.

Upvotes: 1

Related Questions