This article mainly introduces the PHP Method for reading and writing XML, which is very simple and practical. For more information, see.
This article mainly introduces the PHP Method for reading and writing XML, which is very simple and practical. For more information, see.
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:
The Code is as follows:
Jack Herrington
DOM reading XML
The Code is as follows:
<? 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 \ n ";
}
?>
Write XML using DOM
The Code is as follows:
<? Php
$ Books = array ();
$ Books [] = array (
'Title' => 'php hacks ',
'Author' => 'Jack Herrington ',
);
$ Doc = new DOMDocument (); // create a dom object
$ Doc-> formatOutput = true;
$ R = $ doc-> createElement ("books"); // create a tag
$ Doc-> appendChild ($ r); // Add the $ r tag to the xml format.
Foreach ($ books as $ book)
{
$ B = $ doc-> createElement ("book"); // create a tag
$ Author = $ doc-> createElement ("author ");
$ Author-> appendChild ($ doc-> createTextNode ($ book ['author']); // add content to the tag
$ B-> appendChild ($ author); // Add the child tag to the parent tag
$ R-> appendChild ($ B); // Add it to the parent tag!
}
Echo $ doc-> saveXML ();
?>
The above are the DOM code for reading and writing XML. Do you know it? If you have any questions, please leave a message for me.
,