P ARSING XML

Two techniques are used for parsing XML documents in PHP:
SAX(Simple API for XML) andDOM
(Document Object Model). By using SAX, the parser
goes through your document and fires events for every start and stop tag or
other element found in your XML document. You decide how to deal with the
generated events. By using DOM, the whole XML file is parsed into a tree that
you can walk through using functions from PHP. PHP 5 provides another way
of parsing XML: the SimpleXML extension. But first, we explore the two
mainstream methods.

We now leave the somewhat boring theory behind and start with an example.
Here, we’re parsing the example XHTML file we saw earlier. We do that by
using the XML functions available in PHP (http://php.net/xml
)
. First, we create
a parser object:
$xml = xml_parser_create('UTF-8');

xml_set_element_handler($xml, 'start_handler', 'end_handler');
xml_set_character_data_handler($xml, 'character_handler');

function start_handler ($xml, $tag, $attributes)
{
global $level;
echo "\n". str_repeat(' ', $level). ">>>$tag";
foreach ($attributes as $key => $value) {
echo " $key $value";
}
$level++;
}


DOM
Parsing a simple X(HT)ML file with a SAX parser is a lot of work. Using the
DOM (http://www.w3.org/TR/DOM-Level-3-Core/) method is much easier, but
you pay a price—memory usage. Although it might not be noticeable in our
small example, it’s definitely noticeable when you parse a 20MB XML file with
the DOM method. Rather than firing events for every element in the XML file.

<?php
 $dom = new DomDocument();
 $dom->load('test2.xml');
 $root = $dom->documentElement;

 process_children($root);

 function process_children($node)
 {
 $children = $node->childNodes;

 foreach ($children as $elem) {
 if ($elem->nodeType == XML_TEXT_NODE) {
 if (strlen(trim($elem->nodeValue))) {
 echo trim($elem->nodeValue)."\n";
 }
} else if ($elem->nodeType == XML_ELEMENT_NODE) {
process_children($elem);
     }
    }
   }
 ?>
The output is the following:
XML Example
Moved to
example.org
.
foo & bar
Related Posts:
  • PHP INTERFACES Class inheritanceenables you to describe a parent-child relationshipbetween classes. For example, you might have a base class  Shapefrom which both Squareand Circlederive. However,  you might often want to add a… Read More
  • parent AND self PHP oops  parent  AND self PHP oops self::refers to the current class and it is usually used to accessstatic members, methods, and constants. parent::refers to the  parent class and it is most often used when wanting … Read More
  • Building Dynamic Images-PHP You want to create an image based on a existing image template and dynamic data typically text). For instance, you want to create a hit counter. Load the template image, find the correct position to properly cente… Read More
  • Php Date or Time Simplest display of date or time is telling your users what time it is. Use the date( ) or strftime( ) strftime( ) says: Wed Oct 20 12:00:00 2004date( ) says: Wed, 20 Oct 2004 12:00:00 -0400 Both strftime( ) and date( )… Read More
  • Create Login page php-Php code  Create Login page php <?php             session_start();             $host="localhost"; // Host name &n… Read More
  • What is array Arrays An arrayin PHP is a collection of key/value pairs.  This means that it maps keys or indexes to values. Array indexescan be either integers or strings whereas values can be of any type. Arrays in PHP are implement… Read More
  • Aarray And multiple array values Aarray And multiple array values array[key_element1] => array(1, 2,3); array[key_element2] => array(4, 5, 6);  associative arrays array[key1] => array(key => value1, key => value2, key => value3); … Read More
  • download a file by php code-PHP download files code Basic example for download a  file by php <?php $file="http://testexample.com/your_test_file.jpg"; // path to your file  header('Content-Type: application/octet-stream'); header('Content-Disposition: attachm… Read More
  • PHP Jobs interview-Common Section PHP Syntax Variables Operators Arrays If/Then Statements Switch Statements For Loops Foreach Loops While Loops Do While Loops User-Defined Functions Object Oriented Programming with PHP… Read More
  • Static Methods-PHP  PHP supports declaring methods as static. Whatthis means is that your static methods are part of the  class and are not bound to any specific object instance and  its properties. Therefore, $this isn’t acce… Read More
  • strtotime php-current time zone strtotime()parsing is always done with the current time zone, unless a different time zone is specified in the string that is parsed:<?phpecho date("H:i T\n", strtotime("09:22")); // shows 09:22 CETecho date("H:i T\n\n", … Read More
  • Php-Configuration Control Through .htaccess The .htaccessfile is very powerful and can control more than just URL structure. For instance, you can control PHP configuration options using the .htaccessfile. To increase the memory allotted to PHP use this command: php_v… Read More
  • PHP Session expire-minutes inactivity PHP Session expire-minutes inactivity session_cache_limiter('public'); session_cache_expire(15); //should expire after 15  minutes inactivity asy way to handle this, is to set a variable to $_SESSION  every time … Read More
  • PHP RSS feed script PHP RSS feed script RSS Reader PHP code function get_feed($link) {     $this->load->helper('text');     $last_update = time();     header('Cache-Control: no-cache, must-… Read More
  • Showing the Local Time in Other Time Zones Showing the Local Time in Other Time Zones Sometimes, you want  to show a formatted time in the current time zone and inother time zones as well. The following script shows a full textual date representation for the U.S… Read More