_php techniques for reading and writing XML DOM code in PHP

Source: Internet
Author: User
Tags fread
Copy Code code as follows:

Reading XML with DOM
$doc = new DOMDocument ();
$doc->load (' Test.xml ');
$books = $doc->getelementsbytagname ("book");
foreach ($books as $book) {
$authors = $book->getelementsbytagname ("author");
$author = $authors->item (0)->nodevalue; The NodeValue property can set or return the value of a node based on the type of the node.
$publishers = $book->getelementsbytagname ("publisher");
$publisher = $publishers->item (0)->nodevalue;
$titles = $book->getelementsbytagname ("title");
$title = $titles->item (0)->nodevalue;
echo "Title: $title <br> Author: $author <br> Publisher: $publisher <br>}

/*
The script first creates a new DOMDocument object and loads the book 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 obtains the nodevalue of author, publisher, and title tags using the Getelementsbyname method. NodeValue is the text in the node. The script then displays these values.
*/
Copy Code code as follows:

Reading XML with the SAX parser
$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 (' Test.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 ']. \ n ";
}

/*
The script first sets the G_books array, which holds all the book and book Information in memory, and the G_elem variable holds the name of the tag that the script is currently working on. The script then defines the callback function. In this example, the callback functions are startelement, endelement, and TextData. Call the startelement and endelement functions individually when the tag is turned on and off. On top of the text between the start and end tags, call textData.
In this example, the startelement tag looks for the book tag and begins a new element in the book array. The TextData function then looks at the current element to see if it is publisher, title, or author tag. If so, the function puts the current text into the current book.
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 contents of the G_books array are output at the end of the script.
*/
Parsing XML with regular expressions
Copy Code code as follows:

$xml = "";
$f = fopen (' Test.xml ', ' R ');
while ($data = Fread ($f, 4096)) {$xml. = $data;}
Fclose ($f);
Preg_match_all ("/\<book\>" (. *?) \<\/book\>/s ", $xml, $bookblocks);
foreach ($bookblocks [1] as $block) {
Preg_match_all ("/\<author\>" (. *?) \<\/author\>/", $block, $author);
Preg_match_all ("/\<title\>" (. *?) \<\/title\>/", $block, $title);
Preg_match_all ("/\<publisher\>" (. *?) \<\/publisher\>/", $block, $publisher);
Echo ($title [1][0]. "-". $author [1][0]. "-". $publisher [1][0]. " \ n ");
}

/*
I never recommend reading XML with regular expressions, but sometimes it is the best way to be compatible, because regular expression functions are always available. Do not read XML directly from the user with a regular expression, because you cannot control the format or structure of such XML. You should always read XML from the user using the DOM library or the SAX parser.
*/
Writing XML with DOM
Copy Code code 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 '
);
$doc = new DOMDocument ();
$doc->formatoutput = true;
$r = $doc->createelement ("books");
$doc->appendchild ($R);
foreach ($books as $book) {
$b = $doc->createelement ("book");
$author = $doc->createelement ("author");
$author->appendchild ($doc->createtextnode ($book [' author ']));
$b->appendchild ($author);
$title = $doc->createelement ("title");
$title->appendchild ($doc->createtextnode ($book [' title ')]);
$b->appendchild ($title);
$publisher = $doc->createelement ("publisher");
$publisher->appendchild ($doc->createtextnode ($book [' publisher ']));
$b->appendchild ($publisher);
$r->appendchild ($b);
}
echo $doc->savexml ();

/*
At the top of the script, the books array is loaded with some examples. This data can be from the user or from the database.
After the sample book is loaded, 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 text nodes to each node. The last step of each book node is to add it back to the root node books.
The real value of using the DOM is that the XML it creates is always well-formed. But what if you can't create XML with the DOM?
XML code
Copy Code code as follows:

<?php
PHP writes XML
$books = Array ();
$books [] = Array (
' title ' => ' PHP Hacks ',
' Author ' => ' Jack Herrington ',
' publisher ' => ' O ' Reilly '
);
$books [] = Array (
' title ' => ' Podcasting Hacks ',
' Author ' => ' Jack Herrington ',
' publisher ' => ' O ' Reilly '
);
?>
<books>
<?php
foreach ($books as $book)
{
?>
<book>
<title><?php Echo ($book [' title ']);?></title>
<author><?php Echo ($book [' author ']);?>
</author>
<publisher><?php Echo ($book [' publisher ']);?>
</publisher>
</book>
<?php
}
?>
</books>

The test.xml used in the instance are as follows:
Copy Code code as follows:

<?xml version= "1.0″encoding=" utf8″?>
<books>
<boo K>
<author>jack herrington</author>
<title>php hacks</title>
<PUBLISHER&G T;o ' reilly</publisher>
</book>
<book>
<author>jack herrington</author> br><title>podcasting hacks</title>
<publisher>o ' reilly</publisher>
</book> Br></books>

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.