Adrian Adrian - 1 month ago 6
PHP Question

Read colon tags values XML PHP

I've already read those topics:
PHP library for parsing XML with a colons in tag names? and
Simple XML - Dealing With Colons In Nodes but i coundt implement those solutions.

<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>


I want to get only itunes:duration and itunes:image. Here is my code:

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

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

foreach ($items as $item) {

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


I tried using
children()
method but when i try to
print_r
it it says that the node no longer exists.

Answer

You should use the children() on the $item element to get it's child-elements:

$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";
}

Output:

TITLE
YESTERDAY
99:99:99
Comments