Read and write XML dom_php tutorials in PHP

Source: Internet
Author: User
There are many techniques that can be used to read and write XML in PHP. This article provides three ways to read XML: Using the DOM Library, using the SAX parser, and using regular expressions. It also describes writing XML using the DOM and PHP text templates.

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

This article provides a short introduction to XML and then explains how to read and write XML in PHP.

   What is XML?

XML is a data storage format. It does not define what data is saved, nor does it define the format of the data. XML simply defines the tags and the attributes of those tags. Well-formed XML tags look like this:

<name> Jack Herrington </name>

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

XML tags that do not contain text look like this:

<powerup/>

There is more than one way to write an item in XML. For example, this tag forms the same output as the previous tag:

<powerUp> </powerUp>

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

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

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

&

XML file containing tags and attributes if formatted as an example, it is well-formed, which means that the token is symmetric and the character is encoded correctly. Listing 1 is an example of well-formed XML.

Listing 1. Examples of XML book columns

            
      
       
       
         Jack herrington 
        
        PHP Hacks  
       
         oreilly
         
       
       
       
       
         Jack Herrington 
        
        podcasting Hacks  
       
         oreilly 
        
       
                 

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

XML documents are correct when the markup structure and contents of an XML document are validated by an external schema file. Schema files can be specified in different formats. For this article, all you need is well-formed XML.

If you think that XML looks much like Hypertext Markup Language (HTML), then you are right. Both XML and HTML are markup-based languages, and they have many similarities. However, it is emphasized that although XML documents may be well-formed HTML, not all HTML documents are well-formed XML. A newline tag (BR) is a good example of the difference between XML and HTML. This newline tag is well-formed HTML, but not well-formed XML:

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

This newline tag is well-formed XML and HTML:

<p> This is a PARAGRAPH<BR/>
With a line break </p>

If you want to write HTML as well-formed XML, follow the Extensible Hypertext Markup Language (XHTML) standard of the Board (see Resources). All modern browsers can present XHTML. Also, it is much easier to use XML tools to read XHTML and find the data in the document than to parse the HTML.

   reading XML using the DOM library

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

Figure 1. Xml DOM Tree of book XML


The books node at the top of the tree has two book sub-tags. In each book, there are several nodes for author, publisher, and title. The author, publisher, and title nodes have text sub-nodes that contain text, respectively.

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

Listing 2. Reading the book XML with the DOM

            
     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 the object using the Load method. The script then uses the Getelementsbyname method to get a list of all the elements under the specified name.

In the book node loop, the script uses the Getelementsbyname method to get the nodevalue of author, publisher, and title tags. NodeValue is the text in the node. The script then displays these values.

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

% PHP e1.php
PHP Hacks-jack herrington-oreilly
Podcasting Hacks-jack herrington-oreilly
%

As you can see, each library block outputs one line. This is a good start. But what if I can't access the XML DOM library?
  reading XML with the SAX parser

Another way to read XML is to use the XML simple API (SAX) parser. Most installations of PHP contain SAX parsers. The SAX parser runs on the callback model. Each time a marker is opened or closed, or whenever the parser sees the text, the user-defined function is recalled with information from the node or text.

The advantage of the SAX parser is that it is really lightweight. The parser does not persist content in memory for a long term, so it can be used for very large files. The disadvantage is that writing a SAX parser callback is a very cumbersome thing to do. Listing 3 shows the code that uses SAX to read the book XML file and display the content.

Listing 3. Reading the book XML with the SAX parser
            <?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 holds all the books and book information in memory, and the G_elem variable saves the script that is currently being processed

http://www.bkjia.com/PHPjc/508477.html www.bkjia.com true http://www.bkjia.com/PHPjc/508477.html techarticle There are many techniques that can be used to read and write XML in PHP. This article provides three ways to read XML: Using the DOM Library, using the SAX parser, and using regular expressions. Also introduced are the use of the DOM and ...

  • 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.