PHP Read and write xml_php instance

Source: Internet
Author: User

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:

Copy Code code as follows:

<name>jack herrington</name>

Dom reads XML

Copy Code code 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";
}
?>

Writing XML with DOM

Copy Code code as follows:

<?php
$books = Array ();
$books [] = Array (
' title ' => ' PHP Hacks ',
' Author ' => ' Jack Herrington ',
);
$doc = new DOMDocument (); Creating a DOM Object
$doc->formatoutput = true;

$r = $doc->createelement ("books");//Create label
$doc->appendchild ($R); Add the label to the XML format.

foreach ($books as $book)
{
$b = $doc->createelement ("book"); Creating labels
$author = $doc->createelement ("author");
$author->appendchild ($doc->createtextnode ($book [' author '])); Add content to a label
$b->appendchild ($author); Add a child label to a parent tag


$r->appendchild ($b); Join the parent Tag!
}

echo $doc->savexml ();
?>

The above is the 2 paragraphs read and write the XML DOM code, the small partners understand no, have any questions can give me a message

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.