我在尝试阅读和解析此提要时遇到问题: 一些 XML Feed
由于某种原因,函数 SimpleXMLElement 返回空节点。我使用 file_get_contents 读取 URL,然后使用 SimpleXMLElement。
这里有一个例子:
<?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 不能理想地处理 XML 名称空间(即带有冒号的标签),因此遗憾的是您不能这样做:
$id = (string) $item->{'cnn-article:id'};
您应该能够通过使用 children() 选择器并传递一个真值作为第二个参数来获取该字段:
$id = (string) $item->children('cnn-article', true)->id;
或者,如果您要使用该标签中的一堆字段:
$cnn = $item->children('cnn-article', true);
$id = (string) $cnn->id;
$url = (string) $cnn->url;
$slug = (string) $cnn->slug;
$createdDate = (string) $cnn->{'created-date'};