PHP Operation XML

Source: Internet
Author: User

PHP Operation XML

I. Using simplexml to manipulate XML

(1) Creating XML

$xml = <<<xml

<?xml encoding= ' utf-8 ' version= ' 1.0 '?>

Xml;

$s _xml = new SimpleXMLElement ($xml);

(2) generate XML $s _xml->asxml (' test.xml ');

(3) load XML $sxml = simplexml_load_file (' test.xml ');

(4) parsing XML $sxml->asxml ();

(5) read out the XML $sxml node name, if there are more than one node in the same node after the Subscript: section name [subscript number], Note that the subscript is starting from 0; if a node contains multi-level nodes, it can be accessed by using the section Name. The default is the first One.

(6) Get node Tag properties

$sxml-node name [nodes subscript]-> section name->attributes () [subscript]; The default is the first

(7) using XPath to get a node

$version = $sxml->xpath ('/root node/byte point ');

The next access method is the same as Above.

Ii. using DOMDocument to manipulate XML

1, read the external XML to operate

(1) creating a DOM object

$dom = new DOMDocument ();

(2) Loading XML

$dom->load (' Test.xml ');

(3) Read node

$version = $dom->getelementsbytagname (' version ');

(4) get the value of the corresponding node

Echo $version->item (subscript number)->nodevalue;

2. Create an internal XML operation

declaring XML

$_doc = new DOMDocument (' 1.0 ', ' Utf-8 ');

Typesetting format

$_doc->formatoutput = true;

Create a primary label

$_root = $_doc->createelement (' root ');

Create a Sub-label

$_version = $_doc->createelement (' version ');

Assign a value to a child tag

$_versiontextnode = $_doc->createtextnode (' 1.0 ');

Put the value in the Sub-tab

$_version->appendchild ($_versiontextnode);

Place a child tag in the parent tag

$_root->appendchild ($_version);

Put the parent element in the XML

$_doc->appendchild ($_root);

Generating an XML file

$_doc->save (' Domcxml.xml ');

PHP Operation XML

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.