php5中,增加了一个simplexml的XML扩展,处理XML起来比较方便,现举例子说明并学习之
一个样本XML
一个样本XML
<?xml version='1.0' ?> <contacts> <contact idx="37"> <name>Ramsey White II</name> <category>Family</category> <phone type="home">301-555-1212</phone> <meta id="x634724" /> </contact> <contact idx="42"> <name>Stratis Kakadelis</name> <category>Friends</category> <phone type="home">240-555-1212</phone> <phone type="work">410-555-7676</phone> <email>skak@example.com</email> <meta id="y49302" /> </contact> <contact idx="57"> <name>Kelly Williamson</name> <category>Friends</category> <phone type="cell">443-555-9999</phone> <email>kwill@example.com</email> <email>dynky@tech.example.com</email> <meta id="w4r302" /> </contact> </contacts>
第一个例子
<?php // Using SimpleXML, read the file into memory: $xml = simplexml_load_file('contacts.xml'); // Let's print out a formatted version of some of this contact data: // Start with an ordered list: echo "<ol>\n"; // Loop over each contact: foreach ($xml->contact as $c) { // Print their name: echo '<li>' . $c->name; // Now start an Unordered list for their phone numbers: echo '<ul>'; // Loop over every phone number for this person: foreach ($c->phone as $p) { // Echo out a line including the type of number: // The attribute will be accesible as if it were an assoc array // entry. Using the entry itself, will echo it's value. echo '<li>', ucfirst($p['type']), ': ', $p, '</li>'; } // Close off the phone list: echo "</ul></li>\n"; } ?>第二个例子是用XPATH的,很简单,没啥好说的,人家的英文注释都说了
<?php
// Using SimpleXML, read the file into memory:
$xml = simplexml_load_file('contacts.xml');// Xpath search to find all 'meta' tags no matter what the depth:
$meta = $xml->xpath('//meta');// Loop over them and output their IDs
foreach ($meta as $m) {
echo "Meta - {$m['id']}<br />\n";
}// Find all email tags within a contact tag from the root of the XML document:
$email = $xml->xpath('/contacts/contact/email');// Loop over them and output the email addreses:
foreach ($email as $e) {
echo "Email - {$e}<br />\n";
}// Finally, find any contact who has a cellphone number
$cell = $xml->xpath('contact/phone[@type="cell"]/..');// Loop over them and output their names:
foreach ($cell as $c) {
echo "Cell Contact - {$c->name}<br />\n";
}
?>