这是我的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>
<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>
我可以检索标题,链接,描述,pubDate等,但无法访问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; ?>
这可能是一个简单的修复,但我已经尝试了几个小时的不同排列。
使用 children() 方法的建议对此有效。
我能够使用以下循环访问每个项目的 pr: 命名空间元素。
$pr = $item->children("pr", true);
foreach ($pr as $pr_key => $pr_value) {
echo $pr_key . " = " . $pr_value . "<br />";
}
问题解决了。