使用PHP和SimpleXML进行RSS解析:如何输入名称空间项


RSS parsing with PHP and SimpleXML: How to enter namespaced items?

我正在解析以下RSS提要(显示相关部分)

<item>
    <title>xxx</title>
    <link>xxx</link>
    <guid>xxx</guid>
    <description>xxx</description>
    <prx:proxy>
        <prx:ip>101.226.74.168</prx:ip>
        <prx:port>8080</prx:port>
        <prx:type>Anonymous</prx:type>
        <prx:ssl>false</prx:ssl>
        <prx:check_timestamp>1369199066</prx:check_timestamp>
        <prx:country_code>CN</prx:country_code>
        <prx:latency>20585</prx:latency>
        <prx:reliability>9593</prx:reliability>
    </prx:proxy>
    <prx:proxy>...</prx:proxy>
    <prx:proxy>...</prx:proxy>
    <pubDate>xxx</pubDate>
</item>
<item>...</item>
<item>...</item>
<item>...</item>
使用php代码
$proxylist_rss = file_get_contents('http://www.xxx.com/xxx.xml');
$proxylist_xml = new SimpleXmlElement($proxylist_rss);
foreach($proxylist_xml->channel->item as $item) {
    var_dump($item); // Ok, Everything marked with xxx
    var_dump($item->title); // Ok, title
    foreach($item->proxy() as $entry) {
        var_dump($entry); //empty
    }
}

虽然我可以访问所有标有xxx的内容,但我不能访问prx:proxy中的任何内容-主要是因为:不能存在于有效的php varname中。

问题是如何到达prx:ip,例如

谢谢!

看一下SimpleXMLElement::children,您可以使用它访问命名空间元素。

例如:-

<?php
$xml = '<xml xmlns:prx="http://example.org/">
<item>
    <title>xxx</title>
    <link>xxx</link>
    <guid>xxx</guid>
    <description>xxx</description>
    <prx:proxy>
        <prx:ip>101.226.74.168</prx:ip>
        <prx:port>8080</prx:port>
        <prx:type>Anonymous</prx:type>
        <prx:ssl>false</prx:ssl>
        <prx:check_timestamp>1369199066</prx:check_timestamp>
        <prx:country_code>CN</prx:country_code>
        <prx:latency>20585</prx:latency>
        <prx:reliability>9593</prx:reliability>
    </prx:proxy>
</item>
</xml>';
$sxe = new SimpleXMLElement($xml);
foreach($sxe->item as $item)
{
    $proxy = $item->children('prx', true)->proxy;
    echo $proxy->ip; //101.226.74.169
}
安东尼。

我只要去掉"prx:"…

$proxylist_rss = file_get_contents('http://www.xxx.com/xxx.xml');
$proxylist_rss = str_replace('prx:', '', $proxylist_rss);
$proxylist_xml = new SimpleXmlElement($proxylist_rss);
foreach($proxylist_xml->channel->item as $item) {
    foreach($item->proxy as $entry) {
        var_dump($entry);
    }
}
http://phpfiddle.org/main/code/jsz-vga

试一下:

$proxylist_rss = file_get_contents('http://www.xxx.com/xxx.xml');
$feed = simplexml_load_string($proxylist_rss);
$ns=$feed->getNameSpaces(true);
foreach ($feed->channel->item  as $item){
    var_dump($item);
    var_dump($item->title); 
    $proxy = $item->children($ns["prx"]);
    $proxy = $proxy->proxy;
    foreach ($proxy as $key => $value){
        var_dump($value);
    }
}