I have a problem with I trying to read and parse this feed: Some XML Feed
for some reason the function SimpleXMLElement returns empty nodes. I am using file_get_contents to read the URL and then SimpleXMLElement.
Here an example:
<?php
// URL feed XML
$url = 'some xml feed';
$xml_content = file_get_contents($url);
if ($xml_content === false) {
echo "No XML content.";
exit;
}
// Parser the XML
$xml = new SimpleXMLElement($xml_content);
foreach ($xml->channel->item as $item) {
$title = (string) $item->title;
$id = (string) $item->{'cnn-article:id'};
$description = (string) $item->description;
// Hacer lo que necesites con los datos
echo "Title: $title<br>";
echo "ID: $id<br>";
echo "Description: $description<br>";
}
?>
SimpleXML doesn't handle XML namespaces (i.e., tags with colons) ideally, so you can't do this unfortunately:
$id = (string) $item->{'cnn-article:id'};
You should be able to grab the field by using the children() selector and passing a truthy value as the second parameter:
$id = (string) $item->children('cnn-article', true)->id;
Or perhaps, if you're going to use a bunch of the fields within that tag:
$cnn = $item->children('cnn-article', true);
$id = (string) $cnn->id;
$url = (string) $cnn->url;
$slug = (string) $cnn->slug;
$createdDate = (string) $cnn->{'created-date'};