cURL / fopen / file() etc

software development

#1

Someone asked about a cURL alternative to PHP’s file() function on the DreamHost Wiki. I’ve run a few tests, and I’ve come up with a suitable alternative that works like this:

[code]<?php
$ch = curl_init();
$timeout = 5; // set to zero for no timeout
curl_setopt ($ch, CURLOPT_URL, ‘http://example.com’);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
$lines = array();
$lines = explode("\n", $file_contents);

// display file line by line
foreach($lines as $line_num => $line) {
echo “Line # {$line_num} : “.htmlspecialchars($line).”
\n”;
}
?>[/code]I tested it on my Atom feed and it seemed to work as expected.


Simon Jessey
Keystone Websites (business site) | si-blog (personal site with affiliate links)