note 40918 added to ref.xml

From: Date: Fri, 19 Mar 2004 03:36:44 +0000
Subject: note 40918 added to ref.xml
Groups: php.notes 
Request: Send a blank email to php-notes+get-67043@lists.php.net to get a copy of this message
I wrote a simple xml parser mainly to deal with rss version 2. I found lots of examples on the net, but they were all masive and bloated and hard to manipulate. Output is sent to an array, which holds arrays containg data for each item. Obviously, you will have to make modifications to the code to suit your needs, but there isnt a lot of code there, so that shouldnt be a problem. <?php $currentElements = array(); $newsArray = array(); readXml("./news.xml"); echo("<pre>"); print_r($newsArray); echo("</pre>"); // Reads XML file into formatted html function readXML($xmlFile) { $xmlParser = xml_parser_create(); xml_parser_set_option($xmlParser, XML_OPTION_CASE_FOLDING, false); xml_set_element_handler($xmlParser, startElement, endElement); xml_set_character_data_handler($xmlParser, characterData); $fp = fopen($xmlFile, "r"); while($data = fread($fp, filesize($xmlFile))){ xml_parse($xmlParser, $data, feof($fp));} xml_parser_free($xmlParser); } // Sets the current XML element, and pushes itself onto the element hierarchy function startElement($parser, $name, $attrs) { global $currentElements, $itemCount; array_push($currentElements, $name); if($name == "item"){$itemCount += 1;} } // Prints XML data; finds highlights and links function characterData($parser, $data) { global $currentElements, $newsArray, $itemCount; $currentCount = count($currentElements); $parentElement = $currentElements[$currentCount-2]; $thisElement = $currentElements[$currentCount-1]; if($parentElement == "item"){ $newsArray[$itemCount-1][$thisElement] = $data;} else{ switch($name){ case "title": break; case "link": break; case "description": break; case "language": break; case "item": break;}} } // If the XML element has ended, it is poped off the hierarchy function endElement($parser, $name) { global $currentElements; $currentCount = count($currentElements); if($currentElements[$currentCount-1] == $name){ array_pop($currentElements);} } ?> ---- Manual Page -- http://www.php.net/manual/en/ref.xml.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+40918 Delete -- http://master.php.net/manage/user-notes.php?action=delete+40918&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+40918&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#67043) next »