Tag Archives: file_get_contents

Using simplexml_load_file with cURL

The PHP function, simplexml_load_file, converts an XML document into an object. This function and file_get_contents uses a similar method, which makes it relatively slower than cURL. There are two different methods to use simplexml_load_file with cURL.

Method 1

As discussed before, you can easily implement cURL into PHP. Using that function along with the following code, you can use simplexml_load_file with cURL.

<?php
$url = 'http://feeds.feedburner.com/fusionswift';
$xml = simplexml_load_string(curl_get_contents($url));
?>

Method 2

It is also possible to use a function which replaces simplexml_load_file. You can use the following code as a full replacement for simplexml_load_file.

<?php
function simplexml_load_file_curl($url) {
	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	$xml = simplexml_load_string(curl_exec($ch));
	return $xml;
}

$url = 'http://feeds.feedburner.com/fusionswift';
$xml = simplexml_load_file_curl($url);
?>

cURL vs file_get_contents

PHP offers two main options to get a remote file, curl and file_get_contents. There are many difference between the two. Curl is a much faster alternative to file_get_contents.

Using file_get_contents to retrieve http://www.example.com/ took 0.198035001755 seconds. Meanwhile, using curl to retrieve the same file took 0.025691986084 seconds. As you can see, curl is much faster.

Using curl can be quite complicated, especially since it requires many lines of code. Here’s a function to simplify the process.

<?php
function curl_get_contents($url) {
	// Initiate the curl session
	$ch = curl_init();
	// Set the URL
	curl_setopt($ch, CURLOPT_URL, $url);
	// Removes the headers from the output
	curl_setopt($ch, CURLOPT_HEADER, 0);
	// Return the output instead of displaying it directly
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	// Execute the curl session
	$output = curl_exec($ch);
	// Close the curl session
	curl_close($ch);
	// Return the output as a variable
	return $output;
}
?>

This function is just like file_get_contents. To use it, use the following piece of code:

<?php
$output = curl_get_contents('http://www.example.com/');
echo $output;
?>