读取冒号标签值XML PHP

时间:2016-10-17 23:26:28

标签: php xml

我已经阅读过这些主题: PHP library for parsing XML with a colons in tag names?Simple XML - Dealing With Colons In Nodes但我要实施这些解决方案。

<item>
<title> TITLE </title>
<itunes:author> AUTHOR </itunes:author>
<description> TEST </description>
<itunes:subtitle> TEST </itunes:subtitle>
<itunes:summary> TEST </itunes:summary>
<itunes:image href="yoyoyoyo.jpg"/>
<pubDate> YESTERDAY </pubDate>
<itunes:block>no</itunes:block>
<itunes:explicit>no</itunes:explicit>
<itunes:duration>99:99:99</itunes:duration>
<itunes:keywords>key, words</itunes:keywords>
</item>

我想只获得itunes:duration和itunes:image。这是我的代码:

$result = simplexml_load_file("http://blablabla.com/feed.xml");

$items = $result->xpath("//item");

foreach ($items as $item) {

    echo $item->title;
    echo $item->pubDate;
}

我尝试使用children()方法,但当我尝试print_r时,它表示节点已不再存在。

2 个答案:

答案 0 :(得分:2)

您应该使用% Sample y values y = [1;9;5;6;3] % Resulting matrix m = bsxfun(@eq, 1:10, y) m = 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 0 0 0 元素上的children()来获取它的子元素:

$item

输出:

$str =<<< END
<item>
<title> TITLE </title>
<itunes:author> AUTHOR </itunes:author>
<description> TEST </description>
<itunes:subtitle> TEST </itunes:subtitle>
<itunes:summary> TEST </itunes:summary>
<itunes:image href="yoyoyoyo.jpg"/>
<pubDate> YESTERDAY </pubDate>
<itunes:block>no</itunes:block>
<itunes:explicit>no</itunes:explicit>
<itunes:duration>99:99:99</itunes:duration>
<itunes:keywords>key, words</itunes:keywords>
</item>
END;

$result = @simplexml_load_string($str);

$items = $result->xpath("//item");

foreach ($items as $item) {
    echo $item->title . "\n";
    echo $item->pubDate . "\n";
    echo $item->children()->{'itunes:duration'} . "\n";
}

答案 1 :(得分:0)

如果Dekel不为某人工作,那么这就是我的替代解决方案。

使用方法getNamespaces

$result = simplexml_load_file("http://blablabla.com/feed.xml");

$items = $result->xpath("//item");

foreach ($items as $item) 
{

    $itunesSpace = $item->getNameSpaces(true);
    $nodes = $item->children($itunesSpace['itunes']);

    //TEST
    echo $nodes->subtitle

    //99:99:99
    echo $nodes->duration

    //If you want the image Href

    $imageAux = $nodes->image->attributes();
    //yoyoyoyo.jpg
    echo $imageAux['href'];
}
相关问题