Archive:PHP and MySQL Programming/XML and PHP: Difference between revisions
wikademia>Ralfe No edit summary |
wikademia>Ralfe |
||
| Line 140: | Line 140: | ||
== Parsing XML Documents == | == Parsing XML Documents == | ||
We have seen the steps needed to successfully parse a XML document with PHP. Lets take a moment to reflect on how these steps are interconnected. | |||
When a XML parser is initialized, php will go through the XML file. When a starting tag is found, a predefined function created by you, the programmer, is called. The same thing happens when php encounters the text between tags, and the end tags. | |||
Here is a complete example of parsing XML documents. This example is a RSS reader which can be used to display News Articles from any RSS feed which conforms to RSS 1.0 standards. | |||
=== Example === | |||
<html> | |||
<head> | |||
<title> Google Articles </title> | |||
</head> | |||
<body> | |||
<h2>Google Articles</h2> | |||
<dl> | |||
<?php | |||
$insideitem = false; | |||
$tag = ""; | |||
$title = ""; | |||
$description = ""; | |||
$link = ""; | |||
function startElement($parser, $name, $attrs) { | |||
global $insideitem, $tag, $title, $description, $link; | |||
if ($insideitem) { | |||
$tag = $name; | |||
} | |||
elseif ($name == "ITEM") { | |||
$insideitem = true; | |||
} | |||
} | |||
function endElement($parser, $name) { | |||
global $insideitem, $tag, $title, $description, $link; | |||
if ($name == "ITEM") { | |||
printf("<dt><b><a href='%s'>%s</a></b></dt>", | |||
trim($link),trim($title)); | |||
printf("<dd>%s</dd>", trim($description)); | |||
$title = ""; | |||
$description = ""; | |||
$link = ""; | |||
$insideitem = false; | |||
} | |||
} | |||
function characterData($parser, $data) { | |||
global $insideitem, $tag, $title, $description, $link; | |||
if ($insideitem) { | |||
switch ($tag) { | |||
case "TITLE": | |||
$title .= $data; | |||
break; | |||
case "DESCRIPTION": | |||
$description .= $data; | |||
break; | |||
case "LINK": | |||
$link .= $data; | |||
break; | |||
} | |||
} | |||
} | |||
$xml_parser = xml_parser_create(); | |||
xml_set_element_handler($xml_parser, "startElement", "endElement"); | |||
xml_set_character_data_handler($xml_parser, "characterData"); | |||
# $fp = fopen("http://www.newsforge.com/index.rss", 'r') | |||
$fp = fopen("http://news.google.co.za/nwshp?hl=en&tab=wn&q=&output=rss", 'r') | |||
or die("Error reading RSS data."); | |||
while ($data = fread($fp, 4096)) { | |||
xml_parse($xml_parser, $data, feof($fp)) | |||
or die(sprintf("XML error: %s at line %d", | |||
xml_error_string(xml_get_error_code($xml_parser)), | |||
xml_get_current_line_number($xml_parser))); | |||
} | |||
fclose($fp); | |||
xml_parser_free($xml_parser); | |||
?> | |||
</dl> | |||
</body> | |||
</html> | |||
== Dumping Database Contents into an XML File == | == Dumping Database Contents into an XML File == | ||