Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a downloaded file from ftp server is not shoing data after using fgetcsv function

Tags:

php

curl

ftp

I am using a cURL request for downloading a CSV file from an FTP server.

I have downloaded my file in my webroot folder (in my given path).

But when I am trying to read the CSV data from the file it isn't showing anything. $leadDir is path of my downloaded file.

if ($fp = fopen($leadDir, "r")) {
    echo $fp;
    echo "come after fopen";
    while ($CSVData = fgetcsv($fp)) {
        echo "</br>";
        echo "come after fgetcsv";
    }
}

It is not going inside the while loop.

I have also checked the file permissions, I have given it 777 permissions.

Where is it going wrong?

like image 425
Javascript Coder Avatar asked Aug 13 '12 07:08

Javascript Coder


3 Answers

the code should be ok, so my best answer is that the path is incorrect, try something like

$cwd = getcwd();
$leadDir = $cwd.'/relativePathToFile';

if(file_exists($leadDir)){
    if (($fp = fopen($leadDir, "r"))) {
        echo $fp;
        echo "come after fopen";
        while ($CSVData = fgetcsv($fp)) {
            echo "</br>";echo "come after fgetcsv";
        } 
    }
 }
like image 189
Copacel Verde Avatar answered Sep 28 '22 08:09

Copacel Verde


Your code looks like it should work. Here is the code I would use:

<?php
if($handle = fopen('test.csv', 'r')) {
    $data = fgetcsv($handle);
    if($data) {
        echo '<pre>';
        var_dump($data);
        echo '</pre>';
    }
}
?>

Try executing this code:

var_dump(file_exists($leadDir));

If the file exists, it will output

bool(true)

otherwise it will output

bool(false)

Also, is $leadDir a directory or a file?

like image 33
uınbɐɥs Avatar answered Sep 28 '22 06:09

uınbɐɥs


fgetcsv() returns NULL if an invalid handle is supplied or FALSE on other errors, including end of file.

Try with:

if (($fp = fopen($leadDir, "r")) !== FALSE) {
    echo $fp;
    echo "come after fopen";
    while (($CSVData = fgetcsv($fp,1000,',')) !== FALSE) {
        echo "</br>";
        echo "come after fgetcsv";
    }
}

If it still does not enter in the while loop, try to check the end of file of the CSV.

Note: If PHP is not properly recognizing the line endings when reading files either on or created by a Macintosh computer, enabling the auto_detect_line_endings run-time configuration option may help resolve the problem. (source PHP.net)

like image 45
matteomattei Avatar answered Sep 28 '22 06:09

matteomattei