简体   繁体   中英

Parsing XML data with Namespaces with PHP

Here's my 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>

I can retrieve the title, link, description, pubDate, etc. but cannot get to the pr:City or pr:State nodes.

This is able to access the city name, but there's not always a city in the XML, so incrementing my counter doesn't work. I simply just want to get those items and display them if they exist.

  $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; ?>

This is probably a simple fix, but I've tried different permutations for hours now.

The suggestion to use the children() method was what worked for this.

I was able to access the pr: namespace elements per item by using the following loop.

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

Problem solved.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM