PHP XmlReader simplexml DOMDocument Reading XML Example

Source: Internet
Author: User
Tags foreach new set object model php regular expression regular expression xml example

There are two traditional ways to deal with XML files: SAX and DOM. SAX based on the event trigger mechanism, a scan of the XML file, complete the processing to be done; Dom constructs the entire XML file as a DOM tree, which is processed by traversing the DOM tree. These two methods have advantages and disadvantages, SAX processing ideas relatively abstract, DOM processing process relatively cumbersome, are not very suitable for beginners to get started. PHP5 introduced a new set of XML processing functions, namely SimpleXML. As a matter of fact, SimpleXML itself is small and lean, only provides a small number of method functions, but with it to deal with the XML file function is very powerful, the operation is very simple.

One, what is Xml,xml's purpose?

XML (extensible Markup Language) expands the markup language, which, like HTML, is SGML (Standard generalized Markup Language, Standard Universal Markup Language). XML is a cross-platform, content-dependent technology in an Internet environment and a powerful tool for dealing with structured document information at the moment. Extensible Markup Language XML is a simple data storage language that uses a series of simple tags to describe data that can be built in a convenient way, although XML takes up more space than binary data, but XML is extremely simple and easy to master and use.
XML can be used to store data, to exchange data, to prompt data for many kinds of applications, and so on.

Second, the way PHP reads XML

XML source files

The code is as follows Copy Code
<?xml version= "1.0" encoding= "UTF-8"?>
<zhangying>
<name> Zhang Ying </name>
<sex> male </sex>
<old>28</old>
</zhangying>
<tank>
<name>tank</name>
<sex> male </sex>
<old>28</old>
</tank>

1) DOMDocument Read XML

The code is as follows Copy Code
<?php
$doc = new DOMDocument ();
$doc->load (' person.xml '); reading XML files

$humans = $doc->getelementsbytagname ("humans"); An array of objects to get the humans label

foreach ($humans as $human)
{
$names = $human->getelementsbytagname ("name"); An array of objects that gets the label for name
$name = $names->item (0)->nodevalue; Get the values in node, such as <name> </name>

$sexs = $human->getelementsbytagname ("sex");
$sex = $sexs->item (0)->nodevalue;

$olds = $human->getelementsbytagname ("old");
$old = $olds->item (0)->nodevalue;

echo "$name-$sex-$old \ n";

}
?>

2) simplexml Read XML

The code is as follows Copy Code
<?php
$xml _array=simplexml_load_file (' person.xml '); Reads data from XML into an array object

foreach ($xml _array as $tmp) {
echo $tmp->name. " -". $tmp->sex." -". $tmp->old." <br> ";
}

?>

3 Use PHP Regular expression to memorize the data

The code is as follows Copy Code
<?php
$xml = "";
$f = fopen (' person.xml ', ' R ');
while ($data = Fread ($f, 4096)) {
$xml. = $data;
}
Fclose ($f);
Read Data above
Preg_match_all ("/\
foreach ($humans [1] as $k => $human)
{
Preg_match_all ("/\<name\>" (. *?)             \<\/name\>/", $human, $name); Match a name
Preg_match_all ("/\<sex\>" (. *?)                        \<\/sex\>/", $human, $sex); Match a gender
Preg_match_all ("/\<old\>" (. *?)                        \<\/old\>/", $human, $old); Match out of age
}

foreach ($name [1] as $key => $val) {
echo $val. "-". $sex [$key][1]. "-" $old [$key][1]. " <br> ";
}
?>

4) XmlReader to read XML data

The code is as follows Copy Code

<?php
$reader = new XMLReader ();
$reader->open (' person.xml '); Reading XML data
$i = 1;
while ($reader->read ()) {//is read
if ($reader->nodetype = = Xmlreader::text) {//Determine node type
if ($i%3) {
Echo $reader->value; Gets the value of node
}else{
echo $reader->value. " <br> ";
}
$i + +;
}
}
?>


Manipulating XML using DOMDocument

1. DOMDocument parsing XML

The code is as follows Copy Code

Create a DOMDocument ()

$_doc = new DOMDocument ();

Load XML

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

Take version label

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

Echo $_version->item (2)->nodevalue;

Traversing the version label

foreach ($_version as $v) {

Echo $v->nodevalue;

}

2. DOMDocument Generate XML

declaring XML

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

Typesetting format

$_doc->formatoutput = true;

Create a primary label

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

Create a first level label version

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

Assigning values to the version label

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

Put the value in the version label

$_version->appendchild ($_versiontextnode);

Put the first-level label version in Root

$_root->appendchild ($_version);

Write primary tags to XML

$_doc->appendchild ($_root);

Generate XML

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


In many cases, hand-generated markup requires that the document be generated from top to bottom, and that the label is complete, starting and closing tags. Although some PHP functions or classes can improve, PHP also provides a set of more helpful built-in objects and functions. The Document Object model, which provides a tree-like structure, makes it easy to create and process labels.

Third, summary

There are many ways to read XML, simply to name a few. The above four methods are able to read the data in the label,<name> Zhang Ying </name> But their focus is different, the first three methods to read the XML function is designed to read the value in the tag, Equivalent to the text () method in jquery, and XmlReader he's not quite the same, his focus is not on reading the value in the tag, and reading the tag's properties, and putting the data to be transferred in the attribute (though the method I wrote above is still the value in the tag, because the XML file is already given, I don't want to get out of the XML file. For example,
<data name= ' Zhang Ying '   sex= ' old= ' ></data>
XmlReader is designed to read the value of name sex old in data. Reading the <data></data> content is rather troublesome. He is equivalent to attr (') in jquery;

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.