Prashant Singh
Prashant Singh

Reputation: 3793

Use of Php function file_get_contents

I have to crawl some values from a website. Should I use curl for that or file_get_contents ??

I am getting some warning with file_get_contents at my localhost .

Any help will be appreciated

Upvotes: 0

Views: 364

Answers (3)

Darvex
Darvex

Reputation: 3644

file_get_contents should be just fine for that purpose

Upvotes: 0

Prashant Singh
Prashant Singh

Reputation: 3793

I think Curl is more preferable, as compared to file_get_contents as you can set headers, request methods like POST or GET, follow redirection etc. So, curl will be advisble

<?php
$ch = curl_init();
    $timeout = 5;
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
    $data = curl_exec($ch);
    curl_close($ch);
    echo $data;
?>

Upvotes: 1

Billy Moon
Billy Moon

Reputation: 58619

If you have basic requirements, I would favor file_get_contents. If you need to set headers, and request method etc... I would recommend using curl.

In your case, I think file_get_contents is enough.

Alternatively, you can use file which returns an array of lines from the retrieved file. It works with locally accessible files, and also with remote urls. I often find it more convenient to loop over an array of lines, than to deal with the whole file in one block - so this might be your best option.

<?php
  foreach(file('http://example.com/the-file.ext') as $line){
    // do something with $line
  }
?>

Upvotes: 3

Related Questions