I have a CSV file which I am trying to parse into an array using PHP. Here is my code:
<?php
echo "hi";
$csvData = file_get_contents('2.csv');
$lines = explode(PHP_EOL, $csvData);
$array = array();
$x=0;
foreach ($lines as $line) {
$array[] = str_getcsv($line);
$x=$x+1;
}
echo $x;
print_r($array);
echo "<font size=\"10\" color=\"green\">DONE</font>";
?>
When I ran this script I was getting a blank page with no error. So I added and print out statement "hi". So now when I run this script I only get "hi"
I did some troubleshooting and I found out that this line
$array[] = str_getcsv($line);
Specifically the $array[]
is giving me the problem. Here is a link of the script in action
Try using fgetcsv
instead of exploding on PHP_EOL
file contents. e.g.:
$fh = fopen('2.csv', "r");
$lines = array();
while ($row = fgetcsv($fh)) {
$lines[] = $row;
}
echo count($lines);
print_r($lines);
At first, check your php version, because str_getcsv available from php 5.3.0
At second add few lines
error_reporting(E_ALL);
ini_set('display_errors', 'On');
and show output
your file 2.csv is 20MB, probably you are hitting php memory limit like so
2015/05/08 00:22:49 [error] 7202#0: *1164289 FastCGI sent in stderr: "PHP message: PHP Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 11 bytes) in /var/www/xxxxxx.com/so/go.php on line 10" while reading response header from upstream, client: xxx.xxx.xxx.xxx, server: www.xxxxxx.com, request: "GET /so/go.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "xxxxxx.com", referrer: "http://xxxxxx.com/so/"
I'm getting this error on my server.