0

I am reading a CSV file which contain URLs. I am trying to output the result of those URLs but facing strange issue. I can't seem to understand why this code doesn't print variable $output when you try to print item which is on first line.

This is my CSV file containing two records:

www.serverfault.com
www.stackoverflow.com

This is my code

<?php
$myfile = fopen("products.csv", "r") or die("Unable to open file!");

    while(!feof($myfile))
    {
        $myline = fgets($myfile);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $myline);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);

        if($myline == "www.serverfault.com")
        {
            echo $output;
        }
    }
?>

Notice in CSV file the first record is www.serverfault.com and it never prints the $output. If I move this record to second line then it prints $output but then it doesn't print $output for www.stackoverflow.com which is on first line now.

What's going on?

2
  • you're just assuming success. curl_exec returns boolean false on failure, which prints as a zero-length string. if($output === false) { die(curl_error($ch)); } and don't forget to check for whitespace (e.g. linebreaks) on your string. your $myline might actually be www....com\n or something. Commented Oct 26, 2015 at 18:02
  • You were absolutely right about both points. $output was false and it turns out there was a whitespace at the end of URL. Thanks. Please post your comment as answer so I can accept it. Commented Oct 26, 2015 at 18:10

1 Answer 1

1

You're just assuming success. curl_exec returns boolean false on failure, which prints as a zero-length string.

Add this:

if($output === false) {
     die(curl_error($ch));

}

And don't forget to check for whitespace (e.g. linebreaks) on your string. Your $myline might actually be www....com\n or similar.

Sign up to request clarification or add additional context in comments.

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.