PHP Read and write instance code for XML DOM _php Tutorial

Source: Internet
Author: User
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 node.

$publishers = $book->getelementsbytagname ("publisher");
$publisher = $publishers->item (0)->nodevalue;

$titles = $book->getelementsbytagname ("title");
$title = $titles->item (0)->nodevalue;

echo "Title: $title
Author: $author
Publisher: $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.
*/

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

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 a publisher, title, or author tag. If so, the function puts the current text in 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 end of the script outputs the contents of the G_books array.

*/

Parsing XML with regular expressions

$xml = "";
$f = fopen (' Test.xml ', ' R ');
while ($data = Fread ($f, 4096)) {$xml. = $data;}
Fclose ($f);

Preg_match_all ("/\ (. *?) \<\/book\>/s ", $xml, $bookblocks);

foreach ($bookblocks [1] as $block) {
Preg_match_all ("/\ (. *?) \<\/author\>/", $block, $author);
Preg_match_all ("/\ (. *?) \<\/title\>/", $block, $title);
Preg_match_all ("/\ (. *?) \<\/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'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. XML from the user should always be read with a DOM library or SAX parser.
*/

Writing XML in DOM

$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 sample books. 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 a text node for each node. The last step of each book node is to re-add it to the root node books.
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?

XML code

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 '
);
?>


foreach ($books as $book)
{
?>

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





}
?>

The test.xml used in the example are as follows:




Jack Herrington
PHP hacks-bkjia.com
O ' Reilly


Jack Herrington
Podcasting Hacks
O ' Reilly

http://www.bkjia.com/PHPjc/364615.html www.bkjia.com true http://www.bkjia.com/PHPjc/364615.html techarticle read XML $doc with DOM = new DOMDocument (), $doc-load (test.xml), $books = $doc-getelementsbytagname (book); foreach ($boo KS as $book) {$authors = $book-getelementsbytagname (auth ...

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