Using XmlReader to read XML data samples in PHP _php tips

Source: Internet
Author: User

There is an XML file that reads as follows:

Copy Code code as follows:

<?xml version= "1.0"?>
<shows>
<show>
<name>Simpsons</name>
<channel>FOX</channel>
<start>8:00 pm</start>
<duration>30</duration>
</show>
<show>
<name>law & Order</name>
<channel>NBC</channel>
<start>8:00 pm</start>
<duration>60</duration>
</show>
</shows>

Here we use the XmlReader extension to parse and process the file, XmlReader another benefit is to read the data in the form of stream, that is, even in the face of large XML files can still be handled calmly. Here is how we deal with the above documents:

Copy Code code as follows:

$INDEXURL = ' http://www.xxx.com/xxx.xml ';
$reader = new XMLReader ();
$reader->open ($INDEXURL);
$countElements = 0;

while ($reader->read ()) {
if ($reader->nodetype = = xmlreader::element) {
$nodeName = $reader->name;
}
if ($reader->nodetype = = Xmlreader::text &&!empty ($nodeName)) {
Switch ($nodeName) {
Case ' name ':
$name = $reader->value;
Break
Case ' channel ':
$channel = $reader->value;
Break
Case ' start ':
$start = $reader->value;
Break
Case ' duration ':
$duration = $reader->value;
Break
}
}
}
$reader->close ();

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.