Online
 
Thursday, 20 November 2008
 
 

PHP - Fetching Content from an HTTP Source | Print |  E-Mail
 

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.

This entry was posted on . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a comment.
Users' Comments (0)

Comment an article
  Name
  E-mail
   Title
Available characters: 4000
 Notify me of follow-up comments
This image contains a scrambled text, it is using a combination of colors, font size, background, angle in order to disallow computer to automate reading. You will have to reproduce it to post on my homepage
Enter what you see:

No comment posted

Jumbo Coklat
 
Top! Top!