Use PHP to read and write XML DOM

Source: Internet
Author: User

There are many techniques that can be used to read and write XML in PHP. This article provides three methods to read XML: using the DOM library, using the SAX Parser, and using regular expressions. It also describes how to use DOM and PHP text templates to write XML.

Reading and Writing Extensible Markup Language (XML) in PHP may seem a little scary. In fact, XML and all its related technologies may be terrible, but reading and writing XML with PHP is not necessarily a terrible task. First, you need to learn a little about XML-what it is and what it is used. Then, you need to learn how to read and write XML in PHP, and there are many ways to do this.

This article provides a brief introduction to XML and explains how to use PHP to read and write XML.

  What is XML?

XML is a data storage format. It does not define what data to save or define the data format. XML only defines the attributes of tags and these tags. Well-formatted XML markup looks like this:

<Name> Jack Herrington </name>

This <name> flag contains some text: Jack Herrington.

XML tags that do not contain text look like this:

<PowerUp/>

There are more than one way to write something in XML. For example, the output of this tag is the same as that of the previous one:

<PowerUp> </powerUp>

You can also add attributes to the XML tag. For example, the <name> tag contains the first and last attributes:

<Name first = "Jack" last = "Herrington"/>

You can also use XML to encode special characters. For example, the & symbol can be encoded like this:

&

If the XML file containing tags and attributes is formatted as in the exampleWell-formatted, Which means that the mark is symmetric and the character encoding is correct. Listing 1 is an example of a well-formatted XML.

Listing 1. XML library List Example

            <books>            <book>            <author>Jack Herrington</author>            <title>PHP Hacks</title>            <publisher>OReilly</publisher>            </book>            <book>            <author>Jack Herrington</author>            <title>Podcasting Hacks</title>            <publisher>OReilly</publisher>            </book>            </books>            

XML in Listing 1 contains a list of books. The parent tag <books> contains a set of <book> tags. Each <book> tag contains <author>, <title>, and <publisher> tags.

After the XML document's tag structure and content are verified by the external mode file, the XML document is correct. Mode files can be specified in different formats. For this article, all we need is a well-formatted XML.

If XML looks like HTML, that's right. XML and HTML are both tag-based languages with many similarities. However, it is important to note that although XML documents may be well-formed HTML documents, not all HTML documents are well-formed XML documents. Line feed mark (br) is a good example of the difference between XML and HTML. This line feed mark is HTML in good format, but not XML in good format:

<P> This is a paragraph <br>
With a line break </p>

This line feed mark is a well-formatted XML and HTML:

<P> This is a paragraph <br/>
With a line break </p>

To write HTML into XML in the same format, follow the W3C Committee's extensible hypertext markup language (XHTML) standard (see references ). All modern browsers can render XHTML. In addition, you can use XML tools to read XHTML and find the data in the document, which is much easier than parsing HTML.

   Use the DOM library to read XML

The easiest way to read well-formed XML files is to compile them into some PHP-installed Document Object Model (DOM) libraries. The DOM library reads the entire XML document into the memory and uses the node tree to represent it, as shown in 1.

Figure 1. xml dom tree of library XML


The books node on the top of the tree has two book subtags. In each book, there are several nodes: author, publisher, and title. The author, publisher, and title nodes contain text subnodes.

The code for reading the XML file of a book and displaying the content in DOM is shown in List 2.

Listing 2. reading library XML with DOM

            <?php            $doc = new DOMDocument();            $doc->load( books.xml );            $books = $doc->getElementsByTagName( "book" );            foreach( $books as $book )            {            $authors = $book->getElementsByTagName( "author" );            $author = $authors->item(0)->nodeValue;            $publishers = $book->getElementsByTagName( "publisher" );            $publisher = $publishers->item(0)->nodeValue;            $titles = $book->getElementsByTagName( "title" );            $title = $titles->item(0)->nodeValue;            echo "$title - $author - $publisher";            }            ?>            

The script first creates a new DOMdocument object and loads the library XML into this object using the load method. Then, the script uses the getElementsByName method to obtain a list of all elements under the specified name.

In the cycle of the book node, the script uses the getElementsByName method to obtain the nodeValue marked by author, publisher, and title. NodeValue is the text in the node. The script then displays these values.

You can run the PHP script like this on the command line:

% Php e1.php
PHP Hacks-Jack Herrington-OReilly
Podcasting Hacks-Jack Herrington-OReilly
%

As you can see, each book block outputs a row. This is a good start. However, what should I do if I cannot access the XML DOM library?
  Read XML with a SAX Parser

Another way to read XML is to use the XML Simple API (SAX) parser. Most PHP installations contain the SAX Parser. The SAX Parser runs on the callback model. Each time a tag is opened or closed, or each time the parser sees the text, it calls back the User-Defined Function with the node or text information.

The advantage of the SAX Parser is that it is truly lightweight. The parser does not keep content for a long time in the memory, so it can be used for very large files. The disadvantage is that it is very troublesome to write the callback of the SAX Parser. Listing 3 shows the code for reading the XML file of a book using SAX and displaying the content.

Listing 3. Using the SAX Parser to read the XML library
            <?php            $g_books = array();            $g_elem = null;            function startElement( $parser, $name, $attrs )            {            global $g_books, $g_elem;            if ( $name == BOOK ) $g_books []= array();            $g_elem = $name;            }            function endElement( $parser, $name )            {            global $g_elem;            $g_elem = null;            }            function textData( $parser, $text )            {            global $g_books, $g_elem;            if ( $g_elem == AUTHOR ||            $g_elem == PUBLISHER ||            $g_elem == TITLE )            {            $g_books[ count( $g_books ) - 1 ][ $g_elem ] = $text;            }            }            $parser = xml_parser_create();            xml_set_element_handler( $parser, "startElement", "endElement" );            xml_set_character_data_handler( $parser, "textData" );            $f = fopen( books.xml, r );            while( $data = fread( $f, 4096 ) )            {            xml_parse( $parser, $data );            }            xml_parser_free( $parser );            foreach( $g_books as $book )            {            echo $book[TITLE]." - ".$book[AUTHOR]." - ";            echo $book[PUBLISHER]."";            }            ?>            

The script first sets the g_books array, which contains all books and book information in the memory. The g_elem variable saves

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.