这篇文章将为大家详细讲解有关php使用simplexml来解析xml的案例,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
代码如下:
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>http://www.php.cn/;/loc>
<lastmod>2013-06-13 01:20:01</lastmod>
<changefreq>always</changefreq>
<priority>1.0</priority>
</url>
<url>
<loc>http://www.php.cn/;/loc>
<lastmod>2013-06-13 01:20:01</lastmod>
<changefreq>always</changefreq>
<priority>0.8</priority>
</url>
</urlset>
XML;
$simple = simplexml_load_string($xml);
// $url = 'http://www.php230.com/baidu_sitemap1.xml';
// $simple = simplexml_load_file($url);
这里我们可以查看一下 $simple 的格式:
print_r($simple);
SimpleXMLElement Object
(
[url] => Array
(
[0] => SimpleXMLElement Object
(
[loc] => http://www.php.cn/
[lastmod] => 2013-06-13 01:20:01
[changefreq] => always
[priority] => 1.0
)
[1] => SimpleXMLElement Object
(
[loc] => http://www.php.cn/
[lastmod] => 2013-06-13 01:20:01
[changefreq] => always
[priority] => 0.8
)
)
)
我们可以看到结果为对象、数组的格式,这样我们就可以很方便地获取XML中每一个元素的值
foreach ($simple->url as $val){
print $val->loc;
}这里会输出每一项的loc值。
关于“php使用simplexml来解析xml的案例”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。