• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

php5中的simplexml

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
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  />
</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>[email protected]</email>
<meta  />
</contact>
<contact idx="57">
<name>Kelly Williamson</name>
<category>Friends</category>
<phone type="cell">443-555-9999</phone>
<email>[email protected]</email>
<email>[email protected]</email>
<meta  />
</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";
}
?>
 

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
php 简单工厂模式发布时间:2022-07-10
下一篇:
微信现金红包开发PHP发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap