Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Linux Timesaving Techniques For Dummies.pdf
Скачиваний:
59
Добавлен:
15.03.2015
Размер:
15.98 Mб
Скачать

Doing the curl E-shuffle with PHP 415

Doing the curl E-shuffle with PHP

If you read Technique 53, you already know quite a bit about curl. curl is a command line tool that makes it quick and easy to upload and download data from other computers. curl can interact with

Web or FTP servers, secure servers, and even directory servers. The curl project developers have created an easy-to-use library, named libcurl, that you can use to build your own curl-enabled programs. libcurl programs can be written in a number of languages. In the previous technique, you find out how to use libcurl from a C program; in this technique, we show you how to use libcurl from a PHP script.

Combining PHP with curl and XML: An overview

PHP scripts usually run within a Web server (not within a Web browser). It might seem a bit strange for a Web server to connect to another server to retrieve information, but that’s actually a very useful thing to do. You may want to relay information (like news headlines) from a remote server to the Web browser. Or, you may want to translate information

LISTING 54-1: WEATHER REPORT FOR MICROSOFT

you obtain from another server into a more friendly and useful format. Using libcurl from a PHP script makes it easy to retrieve remote information.

Thousands of Web sites publish information in XML format (eXtensible Markup Language). We mention earlier that XML data is somewhat self-identifying; each piece of data is surrounded by a pair of tags that describe the data contained within. For example, suppose you see the following text inside an XML stream:

<Forecast>Sunny</Forecast>

You could reasonably assume that Sunny is a forecast (probably part of a weather forecast). XML was designed to make it easier for programs to make sense of a piece of data. PHP knows how to parse through an XML data stream and pick out the pieces that you’re interested in.

In this section, we show you how to use PHP, curl, and XML to display weather conditions on your Web site.

Checking out the XML file

The Web site www.ejse.com publishes XML weather conditions for your zip code. A typical weather report from EJSE might look like Listing 54-1.

<WeatherInfo>

<Location>Redmond, WA</Location> <IconIndex>26</IconIndex> <Temprature>47°F</Temprature> <FeelsLike>44°F</FeelsLike> <Forecast>Cloudy</Forecast> <Visibility>Unlimited </Visibility> <Pressure>29.43 inches and rising</Pressure> <DewPoint>40°F</DewPoint>

<UVIndex>0 Minimal</UVIndex> <Humidity>77%</Humidity>

<Wind>From the Northwest at 6 mph</Wind> <ReportedAt>Renton, WA</ReportedAt> <LastUpdated>

Thursday, February 26, 2004, at 9:53 AM Pacific Standard Time (Thursday, 12:53 PM EST). </LastUpdated>

</WeatherInfo>

416 Technique 54: Timesaving PHP Tricks

(That’s not a typo; the XML stream misspells temperature.)

Notice that each piece of data is surrounded by a pair of tags that describes the data within. For example, the forecast (Cloudy) is surrounded by the tags

<Forecast> and </Forecast> — that’s the essence of XML.

Downloading and displaying the XML file with a PHP script (and curl)

Listing 54-2 shows a reasonably short PHP script that downloads the current weather conditions for a given zip code (currently hard-coded to 98052) and parses through the XML.

LISTING 54-2: FINDING WEATHER CONDITIONS WITH PHP

1 <?php

2

3 $weather = array();

4

5$xmlData = loadWeather();

6 parseWeather( $weather, $xmlData );

7 displayWeather( $weather );

8

9function loadWeather()

10{

11$url = “http://www.ejse.com/WeatherService/Service.asmx/GetWeatherInfo?zipCode=98052”;

12$curl = curl_init();

13

14curl_setopt( $curl, CURLOPT_URL, $url );

15curl_setopt( $curl, CURLOPT_RETURNTRANSFER, 1 );

17$xmlData = curl_exec( $curl );

19curl_close( $curl );

21return( $xmlData );

22}

24function parseWeather( $weather, $data )

25{

26$parser = xml_parser_create();

28xml_set_element_handler( $parser, “startTag”, “endTag” );

29xml_set_character_data_handler( $parser, “dataHandler” );

31xml_parse( $parser, $data );

33xml_parser_free( $parser );

34}

36function startTag( $parser, $tagName, $tagAttributes )

37{

38global $tag;

Doing the curl E-shuffle with PHP 417

40$tag = $tagName;

41}

42

43function endTag( $parser, $tagName )

44{

45global $tag;

46

47$tag = “”;

48}

49

50function dataHandler( $parser, $data )

51{

52global $weather, $tag;

53

54$weather[ $tag ] = $data;

55}

56

57function displayWeather( $weather )

58{

59echo( “<html>\n” );

60

echo(

“<head>\n” );

 

 

 

61

echo(

“ <title>” );

 

 

 

62

echo(

“Current Conditions At “ . $weather[“LOCATION”] . “</title>\n” );

63

echo(

“</head>\n” );

 

 

 

64

 

 

 

 

 

65

echo(

“<body>\n” );

 

 

 

66

echo(

“<h4>\n” );

 

 

 

67

echo(

“Current Weather for: “ . $weather[“LOCATION”] . “<br>” );

68

echo(

“</h4>\n” );

 

 

 

69

 

 

 

 

 

70

echo(

‘<TABLE CELLPADDING=”2” CELLSPACING=”0” BORDER=1>’ );

 

71

echo(

“<TR><TD>Forecast</TD> <TD>”

. $weather[“FORECAST”]

. “</TD></TR>”

 

);

 

 

 

 

72

echo(

“<TR><TD>Temperature</TD>

<TD>” . $weather[“TEMPRATURE”]

. “</TD></TR>”

 

);

 

 

 

 

73

echo(

“<TR><TD>Wind</TD>

<TD>” . $weather[“WIND”]

. “</TD></TR>”

 

);

 

 

 

 

74

echo(

“<TR><TD>Wind Chill</TD>

<TD>” . $weather[“FEELSLIKE”]

. “</TD></TR>”

 

);

 

 

 

 

75

echo(

“<TR><TD>Dewpoint</TD>

<TD>” . $weather[“DEWPOINT”]

. “</TD></TR>”

 

);

 

 

 

 

76

echo(

“<TR><TD>Pressure</TD>

<TD>” . $weather[“PRESSURE”]

. “</TD></TR>”

 

);

 

 

 

 

77

echo(

“<TR><TD>UV Index</TD>

<TD>” . $weather[“UVINDEX”]

. “</TD></TR>”

 

);

 

 

 

 

78

echo(

“</TABLE>” );

 

 

 

79

echo(

“</body>\n” );

 

 

 

80echo( “</html>\n” );

81}

82

83 ?>

418 Technique 54: Timesaving PHP Tricks

This script is very simple:

Line 5: The script calls loadWeather() to retrieve the current conditions and store them in $xmlData.

Line 6: parseWeather() parses the XML stream and stores the result in $weather.

Line 7: displayWeather() picks apart the $weather array and creates an HTML table that’s sent to the Web browser.

Line 9: The loadWeather() function (starting at line 9) downloads an XML stream from the URL shown on line 11. (Change the zip code at the end of the URL to match the location that you’re interested in.)

Line 12: Before you can start a transfer using libcurl, you initialize the library and save a copy of the handle returned by curl_init().

Lines 14 and 15: Next, you see two calls to curl_setopt(). The first call (line 14) gives the URL to libcurl, and the second call (line 15) tells libcurl that you want to download data and store it in a variable (as opposed to storing the data in a file).

Line 17: curl_exec() starts the download, waits for it to complete, and stores the result in $xmlData. When curl_exec() finishes, $xmlData contains the current weather conditions, in XML form, as shown in Listing 54-1.

Line 19–21: Finally, loadWeather() closes its connection to libcurl (see line 19) and returns the XML data to the caller (line 21).

Line 24: parseWeather() (lines 24–34) expects two parameters: the destination array ($weather) and the raw XML data ($data). parseWeather() doesn’t do any of the hard work itself; instead, it calls on PHP’s XML library to pick apart the XML data.

Line 26: You see a call to the xml_parser_create() function. xml_parser_create() creates a new XML parser and returns a handle. An XML parser doesn’t do much by itself; it just identifies the various pieces of an XML stream. To make use of an XML parser, you have to provide callback functions. When an XML parser recognizes a chunk of data that you’re interested in, it calls the callback function that you provide.

Line 28: The call to xml_set_element_handler() tells the parser that you’re interested in elements (or, as we call them, tags). When the parser finds the beginning of an element, it calls the startTag function. When the parser finds the end of an element, it calls endTag (you see startTag and endTag in a moment).

Here’s a typical XML element:

<Location>Redmond, WA</Location>

When the parser sees <Location>, it calls startTag(); when it sees </Location>, it calls endTag(). The stuff in between the tags is called character data — we can trap that, too (see the call to xml_set_character_ data_handler() at line 29).

Line 31: parseWeather() starts the XML parser with a call to xml_parse(), passing the raw XML data that you want to parse.

Line 32: When xml_parse() completes, the call to xml_parser_free() shuts down the parser and frees up any lingering resources.

Lines 36–42: startTag() and endTag() are simple. When the parser calls startTag(), it sends along the tag name, which you store in a global variable named $tag. The tagAttributes parameter contains XML element attributes (if there are any); the weather information that you’re looking at won’t contain attributes, so you can safely ignore this argument.

Doing the curl E-shuffle with PHP 419

Lines 43–48: The endTag() function (lines 43–48) is called whenever the parser sees an end tag. In this function, you simply set the global variable $tag to an empty string.

Lines 50–56: In between calls to startTag() and endTag(), the XML parser calls dataHandler() to handle the data within the tags. dataHandler() simply stores the data that it’s given (a string contained between a pair of tags) in the $weather associative array.

The process is clear when you follow a typical element through the parser. Say that the parser runs into the following text:

<Location>Redmond, WA</Location>

When the parser sees the start tag, it calls startTag(). startTag() stores the tag name (Location) in the $tag global variable. (Actually, the parser converts all tag names to uppercase, so $tag is set to LOCATION.) Next, the parser calls

dataHandler() with the chunk of text (Redmond, WA) between the start tag and the end tag. dataHandler() stores the data in an element of the $weather array using the tag name as in index into the array. In other words: $weather[“LOCATION”] = “Redmond, WA”. Finally, endTag() wipes out the global $tag name (that’s not strictly necessary, but it makes your code a bit more obvious).

When the parser finishes its work, $weather looks like this:

$weather[“LOCATION”]

= “Redmond, WA”

$weather[“ICONINDEX”]

= “26”

$weather[“TEMPRATURE”]

= “47°F”

$weather[“FEELSLIKE”]

= “44°F”

$weather[“FORECAST”]

= “Cloudy”

$weather[“VISIBILITY”]

= “Unlimited”

...

...

Lines 57–81: The displayWeather() function builds an HTML page that it sends to the Web browser. The result looks similar to Listing 54-3.

LISTING 54-3: WEATHER CONDITIONS IN HTML

<html>

<head>

<title>Current Conditions At Redmond, WA</title> </head>

<body>

<h4>Current Weather for: Redmond, WA<br></h4>

<TABLE CELLPADDING=”2” CELLSPACING=”0” BORDER=1>

<TR><TD>Forecast</TD>

<TD>Cloudy</TD></TR>

<TR><TD>Temperature</TD>

<TD>48°F</TD></TR>

<TR><TD>Wind</TD>

<TD>From the South at 6 mph</TD></TR>

<TR><TD>Wind Chill</TD>

<TD>45°F</TD></TR>

<TR><TD>Dewpoint</TD>

<TD>42°F</TD></TR>

<TR><TD>Pressure</TD>

<TD>30.22 inches and rising</TD></TR>

<TR><TD>UV Index</TD>

<TD>0 Minimal</TD></TR>

</TABLE>

 

</body>

 

</html>

 

 

 

Соседние файлы в предмете Операционные системы