XML Extensions in PHP 5

SimpleXML
A new PHP 5-only extension that excels at parsing RSS files, REST results, and configuration data. If you know the document's format ahead of time, SimpleXML is the way to go. However, SimpleXML supports only a subset of the XML specification.

XPath
This extension allows you to query XML documents like you're searching a database, to find the subset of information that you need and eliminate the unnecessary portions.


 XSLT
A way to take XML documents and transform them into HTML or another output format. It uses XML-based stylesheets to define the templates. XSLT is easily shared among different applications, but has a quirky syntax.

 

  • Reading XML into a tree
  • Reading XML from a stream
  • Creating new XML documents
  • Searching XML with XPath
  • Changing XML into HTML or other output formats with XSLT
  • Validating XML to ensure it conforms to a specification



    Example XML address book
    <?xml version="1.0"?>
    
    <address-book>
    
        <person id="1">
    
            <!--Rasmus Lerdorf-->
    
            <firstname>Rasmus</firstname>
    
            <lastname>Lerdorf</lastname>
    
            <city>Sunnyvale</city>
    
            <state>CA</state>
    
            <email>rasmus@php.net</email>
    
        </person>
    
    
    
        <person id="2">
    
            <!--Zeev Suraski-->
    
            <firstname>Zeev</firstname>
    
            <lastname>Suraski</lastname>
    
            <city>Tel Aviv</city>
    
            <state></state>
    
            <email>zeev@php.net</email>
    
        </person>
    
    </address-book>
     
     
     



    $dom = new DOMDocument;
    
    $dom->preserveWhiteSpace = false;
    
    $dom->load('address-book.xml');
    
    
    
    $root = $dom->documentElement;
    
    
    
    foreach ($root->childNodes as $person) {
    
        process($person);
    
    }

     

    The childNodes attribute is not an array, but a DOMNodeList object. The item( ) method allows you to access individual items, and the length property tells you the number of items in the list.
    This code is equivalent to the foreach loop:
    $people = $root->childNodes;
    
    
    
    for ($i = 0; $i < $people->length; $i++) {
    
        process($people->item($i));
    
    }