Team LiB
Previous Section Next Section

Fetching Content from an HTTP Source

PHP makes fetching content from an HTTP source extremely easy. The standard file, file_get_contents, and fopen functions can all be used to fetch content from a URL. Here's an example:

<?php
 //read the information from the url into the variable $contents
 $contents = file_get_contents("http://fuzzyblog.com/index.php");
?>

If you use the HttpClient library, you can retrieve content one of two ways. The first approach is to use the quickGet method. This method, which can be called without creating an HTTP client object, is a fast and easy way to retrieve content. An example is shown next:

<?php
 $pageContents = HttpClient::quickGet("http://fuzzyblog.com/index.php");
?>

However, like the built-in PHP commands, the quickGet method doesn't allow access to HTTP status codes, nor does it allow access to set the user agent. For this reason, the quickGet method doesn't offer significant advantages over the built-in PHP functions. To use these more advanced features, you need to create an HTTP client object as shown next:

<?php
 require_once "HttpClient.class.php";
 $parts = parse_url ("http://fuzzyblog.com/index.php");
 $host = $parts["host"];
 $path = $parts["path"];
 $client = new HttpClient($host);
 if (!$client->get('/')) {
  die('An error occurred: '.$client->getError());
 }
 $pageContents = $client->getContent();
?>

You'll notice that the preceding PHP programming doesn't have to specify the length of the content to fetch. Although specific low-level HTTP options exist for retrieving content by length (or even by range of bytes), the majority of the time you will request all the content in one chunk and not worry about the length.

    Team LiB
    Previous Section Next Section