Read and write implementation code for XML DOM in PHP _php tutorial

Source: Internet
Author: User
Tags fread
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:
Jack Herrington
This one The tag contains some text: Jack Herrington.
XML tags that do not contain text look like this:

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

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

You can also encode special characters with XML. For example, the,& symbol can be encoded like this:
&
XML files that contain tags and attributes are well-formed if formatted like an example, which means that the tokens are symmetric and the characters are encoded correctly. Listing 1 is an example of well-formed XML.

Listing 1. Examples of XML book columns
Copy CodeThe code is as follows:


Jack Herrington
PHP Hacks
O ' Reilly


Jack Herrington
Podcasting Hacks
O ' Reilly



The XML in Listing 1 contains a list of books. Parent tag Contains a set of tags, each Tags are also included, and <publisher> tags. <BR> 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. <BR> If you think XML looks much like Hypertext Markup Language (HTML), then it's 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: <br><p>this is a paragraph<br> <br>with a line break</p> &L T;br> This newline tag is well-formed XML and HTML: <br><p>this is a paragraph<br/> <br>with a line break</p> <BR> If you want to write HTML as well-formed XML, follow the board's Extensible Hypertext Markup Language (XHTML) standard. 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. <BR><STRONG> the easiest way to read xml</strong> <BR> read a well-formed XML file using the DOM library is to use the Document Object Model (DOM) library compiled into some PHP installation. The DOM library reads the entire XML document into memory and uses the node tree to represent it, as shown in 1. <BR> Figure 1. The books node at the top of the XML DOM Tree <BR><BR> Tree of the book XML has two books child 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. <BR> reading the book XML file and using the DOM to displayThe code shown in Listing 2 shows the following. <BR> Listing 2. Read book XML <br><span style= "Cursor:pointer" onclick= "docopy (' code87375 ') with DOM ><U> copy code </U> The </span> code is as follows: <br><?php <BR> $doc = new DOMDocument (); <BR> $doc->load (' books.xml '); <BR> $books = $doc->getelementsbytagname ("book"); <br>foreach ($books as $book) <br>{<BR> $authors = $book->getelementsbytagname ("author"); <br& gt; $author = $authors->item (0)->nodevalue; <BR> $publishers = $book->getelementsbytagname ("publisher"); <BR> $publisher = $publishers->item (0)->nodevalue; <BR> $titles = $book->getelementsbytagname ("title"); <BR> $title = $titles->item (0)->nodevalue; <br>echo "$title-$author-$publisher \ n"; <br>} <BR>?> <BR> <BR> 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. <BR> in the book node loop, the script uses the Getelementsbyname method to obtain author, publiSher and title tags of the nodevalue. NodeValue is the text in the node. The script then displays these values. <BR> can run PHP scripts like this on the command line: <br>% php e1.php <br>php hacks-jack herrington-o ' Reilly <br>podcastin G Hacks-jack herrington-o ' Reilly <br>% <BR> you can see that each book block output one line. This is a good start. But what if I can't access the XML DOM library? <BR> another way to read XML <BR> read XML with the SAX parser 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 <br>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. <BR> Listing 3. Read the book XML <br><span style= "Cursor:pointer" onclick= "docopy (' code65349 ') with the SAX parser ><U> copy Code </U> The </span> code is as follows: <br><?php <BR> $g _books = Array (); <BR> $g _elem = null; <br>function startelement ($parser, $name, $attrs) <br>{<br>global $g _books, $g _elem; <br>if ($ name = = ' book ') $g _books []= Array (); <BR> $g _elem = $name; <br>} &LT;br>function endElement ($parser, $name) <br>{<br>global $g _elem; <BR> $g _elem = null; <br>} <br>function TextData ($parser, $text) <br>{<br>global $g _books, $g _elem; <br>if ($g _elem = = ' AUTHOR ' | | <BR> $g _elem = = ' PUBLISHER ' | | <BR> $g _elem = = ' TITLE ') <br>{<BR> $g _books[count ($g _books)-1 [$g _elem] = $text; <br>} &lt ; br>} <BR> $parser = Xml_parser_create (); <br>xml_set_element_handler ($parser, "startelement", "endElement"); <br>xml_set_character_data_handler ($parser, "textData"); <BR> $f = fopen (' books.xml ', ' R '); <br>while ($data = fread ($f, 4096)) <br>{<br>xml_parse ($parser, $data); <br>} <br>xml_ Parser_free ($parser); <br>foreach ($g _books as $book) <br>{<br>echo $book [' TITLE ']. "-". $book [' AUTHOR ']. "-"; <br>echo $book [' PUBLISHER ']. \ n "; <br>} <BR>?> <BR> <BR> script first set G_bThe ooks array, which holds all the book and book Information in memory, G_elem the name of the tag that the script is currently processing. The script then defines the callback function. In this example, the callback functions are startelement, endElement, and TextData. When you open and close the tag, call the Startelement and EndElement functions, respectively. Above the text between the start and end tags, call textData. <BR> in this example, the startelement tag looks for the book tag and starts a new element in the book array. The TextData function then looks at the current element to see if it is a publisher, title, or author tag. If so, the function puts the current text in the current book. <BR> to allow parsing to continue, the script creates the parser with the Xml_parser_create function. Then, set the callback handle. The script then reads the file and sends a chunk of the file to the parser. After the file is read, the Xml_parser_free function deletes the parser. The end of the script outputs the contents of the G_books array. <BR> can see that this is much more difficult than writing the same functionality as the DOM. What if there is no DOM library and no SAX library? Is there an alternative? <BR>--------------------------------------------------------------------------------<BR> back to top <br > parsing XML with regular expressions <BR> It is certain that some engineers will criticize me even if this method is mentioned, but it is true that XML can be parsed with regular expressions. Listing 4 shows an example of reading a book file using the Preg_ function. <BR> Listing 4. Read XML <br><span style= "Cursor:pointer" onclick= "docopy (' code4870 ') with regular expressions ><U> copy code </U>< The/span> code is as follows: <br><?php <BR> $xml = ""; <BR> $f = fopen (' books.xml ', ' R '); <br>while ($data = Fread ( $f, 4096)) {$xml. = $data;} <br>fclose ($f); <br>preg_match_all ("/\<book\> (. *?) \<\/book\>/s ", <BR> $xml, $bookblocks); <br>foreach ($bookblocks [1] as $block) <br>{<br>preg_match_all ("/\ (. *?) \<\/author\>/", <BR> $block, $author); <br>preg_match_all ("/\<title\> (. *?) \<\/title\>/", <BR> $block, $title); <br>preg_match_all ("/\<publisher\> (. *?) \<\/publisher\>/", <BR> $block, $publisher); <br>echo ($title [1][0]. "-". $author [1][0]. "-". <BR> $publisher [1][0]. " \ n "); <br>} <BR>?> <BR> <br><br> Notice how short this code is. At the beginning, it reads the file into a large string. Then read each book item with a Regex function. Finally, a Foreach loop is used to cycle through each book block and extract the author, title, and publisher. <BR> So, where is the flaw? The problem with reading XML using regular expression code is that it does not check first to make sure that the XML is well-formed. This means that there is no way to know if the XML is well-formed before reading. Also, some well-formed XML may not match regular expressions, so you must modify them later. <BR> I never recommend reading XML with regular expressions, but sometimes it's the best way to be compatible because regular expression functions are always available. Do not use regular expressions to read XML directly from the user, because there is no control over the format or structure of such XML. Should always use the DOM The library or SAX parser reads XML from the user. <BR>--------------------------------------------------------------------------------<BR> back to top <br > Writing XML <BR> reading XML with the DOM is only part of the equation. How do you write XML? The best way to write XML is to use the DOM. Listing 5 shows how the DOM constructs the book XML file. <BR> Listing 5. Use DOM to write book XML <br><span style= "Cursor:pointer" onclick= "docopy (' code86307 ')" ><U> copy code </U> The </span> code is as follows: <br><?php <BR> $books = Array (); <BR> $books [] = Array (<BR> ' title ' = ' PHP Hacks ', <BR> ' author ' = ' Jack Herrington ', <BR> ' p Ublisher ' + ' O ' Reilly "<BR>); <BR> $books [] = Array (<BR> ' title ' = ' podcasting Hacks ', <BR> ' author ' = ' Jack Herrington ', <b R> ' publisher ' and ' O ' Reilly ' <BR> '; <BR> $doc = new DOMDocument (); <BR> $doc->formatoutput = true; <BR> $r = $doc->createelement ("books"); <BR> $doc->appendchild ($r); <br>foreach ($books as $book) <br>{<BR> $b = $doc->createelement ("book"); <BR> $author = $doc->createelement ("author"); <BR> $author->appendchild (<BR> $doc->createtextnode ($book [' author ']) <BR>); <BR> $b->appendchild ($author); <BR> $title = $doc->createelement ("title"); <BR> $title->appendchild (<BR> $doc->createtextnode ($book [' title ']) <BR>); <BR> $b->appendchild ($title); <BR> $publisher = $doc->createelement ("publisher"); <BR> $publisher->appendchild (<BR> $doc->createtextnode ($book [' publisher ']) <BR>); <BR> $b->appendchild ($publisher); <BR> $r->appendchild ($b); <br>} <br>echo $doc->savexml (); <BR>?> <BR> <br><br> at the top of the script, some sample books are loaded into the books array. This data can be from the user or from the database. <BR> sample book after the load, the script creates a new DOMDocument and adds the root node books to it. The script then creates nodes for each book's author, title, and publisher, and adds a text node for each node. The last step of each book node is to re-add it to the root node books. The end of the <BR> script uses the SaveXML method to output XML to the console. (You can alsoTo create an XML file with the Save method. The output of the script is shown in Listing 6. <BR> Listing 6. The output of the DOM build script <br><span style= "Cursor:pointer" onclick= "docopy (' code68553 ')" ><U> copy code </U>< The/span> code is as follows: <br>php e4.php <br><?xml version= "1.0"?> <BR><books> <br><book > <br>jack herrington</author> <br><title>php Hacks
O ' Reilly


Jack Herrington
Podcasting Hacks
O ' Reilly



The real value of using the DOM is that the XML it creates is always formatted correctly. But what if you can't create XML with the DOM?
--------------------------------------------------------------------------------
Back to top of page
Writing XML in PHP
If the DOM is not available, you can write XML in PHP's text template. Listing 7 shows how PHP constructs the book XML file.
Listing 7. Write the book XML in PHP
Copy CodeThe code is as follows:
$books = Array ();
$books [] = Array (
' Title ' = ' PHP Hacks ',
' Author ' = ' Jack Herrington ',
' publisher ' = ' O ' Reilly '
);
$books [] = Array (
' Title ' = ' Podcasting Hacks ',
' Author ' = ' Jack Herrington ',
' publisher ' = ' O ' Reilly '
);
?>

foreach ($books as $book)
{
?>

<?php Echo ($book [' title ']);?>





}
?>



The top of the script is similar to a DOM script. At the bottom of the script, open the books tag, and then iterate through each book, creating the books tag and all the internal title, author, and publisher tags.
The problem with this approach is to encode the entity. To ensure that the entity is encoded correctly, you must call the Htmlentities function on each project, as shown in Listing 8.
Listing 8. Encode an entity using the Htmlentities function
Copy CodeThe code is as follows:

foreach ($books as $book)
{
$title = htmlentities ($book [' title '], ent_quotes);
$author = htmlentities ($book [' Author '], ent_quotes);
$publisher = htmlentities ($book [' publisher '], ent_quotes);
?>

<?php Echo ($title);?>




}
?>



That's the annoying thing about writing XML with basic PHP. You think you created the perfect XML, but when you try to use the data, you immediately find that some elements are not encoded correctly.
--------------------------------------------------------------------------------
Conclusion
There is always a lot of exaggeration and confusion around XML. But it's not as difficult as you might think-especially in a good language like PHP. After understanding and correctly implementing XML, you will find that there are many powerful tools to use. XPath and XSLT are some of the two tools worth studying.

http://www.bkjia.com/PHPjc/322974.html www.bkjia.com true http://www.bkjia.com/PHPjc/322974.html techarticle 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 ...

  • Related Article

    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.