0
votes

I want to read some data of the latest video on a youtube channel.

So i load the feed with simplexml_load_file and after that I use XPath for navigate to nodes.

$xmlFeed = simplexml_load_file("https://www.youtube.com/feeds/videos.xml?channel_id=UCo0bvu1jzU4WpHS3FglLU8g");

echo $xmlFeed->xpath("//entry[1]/title")[0];
echo $xmlFeed->xpath("//entry[1]/link")[0];
echo $xmlFeed->xpath("//entry[1]/id")[0];

I tried multiple style of XPath and it never work, I also tried to use DOMDocument and DOMXPath classes and it didn't work.

I use similar code for a wordpress rss and all works fine.

What am I wrong?

1

1 Answers

1
votes

As per SimpleXMLElement::xpath's doc page's first comment:

To run an xpath query on an XML document that has a namespace, the namespace must be registered with SimpleXMLElement::registerXPathNamespace() before running the query. If the XML document namespace does not include a prefix, you must make up an arbitrary one, and then use it in your query.

You should therefore do this:

$xmlFeed = simplexml_load_file('https://www.youtube.com/feeds/videos.xml?channel_id=UCo0bvu1jzU4WpHS3FglLU8g');

foreach ($xmlFeed->getDocNamespaces() as $prefix => $namespace) {
    $xmlFeed->registerXPathNamespace($prefix ?: 'default', $namespace);
}

echo $xmlFeed->xpath('//default:entry[1]/default:title')[0];
echo $xmlFeed->xpath('//default:entry[1]/default:link')[0];
echo $xmlFeed->xpath('//default:entry[1]/default:id')[0];

Note: feel free to use something shorter than default if it's inconvenient.