php5中的simplexml

php5中,增加了一个simplexml的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";
}
?>
 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值