【问题标题】:Parsing XML data with Namespaces with PHP使用 PHP 使用命名空间解析 XML 数据
【发布时间】:2016-03-14 20:43:57
【问题描述】:

这是我的 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; ?>

这可能是一个简单的修复,但我已经尝试了几个小时的不同排列。

【问题讨论】:

标签: php xml simplexml


【解决方案1】:

使用 children() 方法的建议对此有用。

通过使用以下循环,我能够访问每个项目的 pr: 命名空间元素。

    $pr = $item->children("pr", true);
        foreach ($pr as $pr_key => $pr_value) {
        echo $pr_key . " = " . $pr_value . "<br />";
    }

问题解决了。

【讨论】:

    猜你喜欢
    • 2012-06-11
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 2021-05-03
    • 2014-01-10
    • 2021-04-06
    相关资源
    最近更新 更多