Fetching a remote XML doc: 4
Source code
1
<?php include('./.config.php');
2 // Four ways to fetch an RSS feed via http: Part 4 of 4
3 // Use the PHP sockets extension to speak HTTP over the wire yourself
4
5 $xml = fetchRss("rss.news.yahoo.com","/rss/oddlyenough");
6 if ($xml) {
7 echo '<pre>'. htmlentities($xml) .'</pre>';
8 } else {
9 die ('document unavailable (or something like that)');
10 }
11
12 function fetchRss($host,$path_to_resource) {
13
14 $sock = fsockopen($host,80,$errno,$errstr,6) ;
15 if (! $sock) { return false; }
16
17 fwrite($sock,
18 "GET $path_to_resource HTTP/1.1\r\nHost: $host\r\nConnection: close\r\n\r\n");
19 // set a flag that tells us whether we're past the HTTP headers
20 $isBody = false;
21 // put the body in $body
22 $body = '';
23 while (!feof($sock)) {
24
25 $data = fgets($sock);
26
27 // if we see the opening xml tag, we are in the
28 // body of the server response
29 if (strstr($data,'<?xml')) {
30 $isBody = true;
31 $body .= $data;
32 continue;
33 }
34 if ($isBody) {
35 $body .= $data;
36 // if we see the closing rss tag,
37 // we do not want any more $data
38 if (stristr($data,'</rss>')) {
39 break;
40 }
41 }
42 }
43 fclose($sock);
44 return $body;
45 }
46 include('./.footer.php')?>
47