0

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

http://euryalosstudios.com/api/new1.php

3
  • Do you have error reporting turned on for your php code ? Commented May 7, 2015 at 20:45
  • 1
    What does var_dump($lines) give you? May be there is no value in $lines ? Commented May 7, 2015 at 20:47
  • 1
    Also, I am not sure if your CSV file is actually comma separated. Maybe you are using a ; as a separator ? Commented May 7, 2015 at 20:50

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.