用PHP解析具有名称空间的XML数据
以下是我的XML:用PHP解析具有名称空间的XML数据,php,xml,simplexml,Php,Xml,Simplexml,以下是我的XML: <?xml version="1.0" encoding="UTF-8"?> <rss version="2.0" xmlns:pr="http://www.prconnect.com"> <channel> <title>Clipping Service</title> <link>http://www.financialcontent.com</link> <descript
<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:pr="http://www.prconnect.com">
<channel>
<title>Clipping Service</title>
<link>http://www.financialcontent.com</link>
<description>Clipping Service</description>
<pubDate>Sun, 13 Mar 2016 16:38:06 -0400</pubDate>
<language>en-us</language>
<item>
<title><![CDATA[Benton Courier]]></title>
<link>http://business.bentoncourier.com/bentoncourier/news/read/31711961/Featured_National_Park_Series</link>
<source url="http://www.bentoncourier.com">http://www.bentoncourier.com</source>
<description><![CDATA[Featured National Park Series: From Yosemite to Tuzi]]></description>
<pubDate><![CDATA[Thu, 03 Mar 2016 13:55:20 -0500]]></pubDate>
<guid>31711961</guid>
<pr:City>Benton</pr:City>
<pr:State>AR</pr:State>
</item>
剪辑服务
http://www.financialcontent.com
剪辑服务
太阳报,2016年3月13日16:38:06-0400
美国英语
http://business.bentoncourier.com/bentoncourier/news/read/31711961/Featured_National_Park_Series
http://www.bentoncourier.com
31711961
本顿
应收账
我可以检索标题、链接、描述、发布日期等,但无法访问pr:City或pr:State节点
这可以访问城市名称,但XML中并不总是有城市,因此递增我的计数器不起作用。我只是想得到这些项目,并显示它们,如果它们存在的话
$i=0;
foreach ( $xml->channel->item as $item ) : ?>
<tr>
<td>
<a href="<?php echo $item->link; ?>"
title="<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->pubDate ); ?>">
<?php echo $item->title; ?>
</a>
</td>
<td>
<?php printf( __( 'Posted %s', 'my-text-domain' ), $item->pubDate ); ?>
</td>
<td><?php
$item->registerXPathNamespace('pr', 'http://www.prconnect.com');
$city = $item->xpath('//pr:City');
echo $city[$i];
$i++
?></td>
</tr>
<?php endforeach; ?>
$i=0;
foreach($xml->channel->item as$item):?>
这可能是一个简单的修复方法,但我已经尝试了几个小时不同的排列方式。建议使用children()方法就是解决这个问题的方法 通过使用以下循环,我能够访问每个项的pr:namespace元素
$pr = $item->children("pr", true);
foreach ($pr as $pr_key => $pr_value) {
echo $pr_key . " = " . $pr_value . "<br />";
}
$pr=$item->children(“pr”,true);
foreach($pr作为$pr\u键=>$pr\u值){
echo$pr_key.“=”$pr_value.“
”;
}
问题已解决。查找子对象()方法可能重复。
方法