从存储模块XML中获取URL标记



我想用PHP 从enclosure标签中获取URL

这是我从RRS馈送中得到的

<item>
<title>Kettingbotsing met auto&#039;s en vrachtwagen op A2</title>
<link>https://www.1limburg.nl/kettingbotsing-met-autos-en-vrachtwagen-op-a2</link>
<description>&lt;p&gt;Drie auto&amp;#39;s en een vrachtauto zijn woensdagochtend met elkaar gebotst op de A2.&amp;nbsp;&amp;nbsp;&lt;/p&gt;</description>
<pubDate>Wed, 21 Nov 2018 07:37:56 +0100</pubDate>
<guid permalink="true">https://www.1limburg.nl/kettingbotsing-met-autos-en-vrachtwagen-op-a2</guid>
<enclosure type="image/jpeg" url="https://www.1limburg.nl/sites/default/files/public/styles/api_preview/public/image_16_13.jpg?itok=qWaZAJ8v" />
</item>

这是我现在使用的代码

$xmlDoc = new DOMDocument();
$xmlDoc->loadXML($xml_string);
foreach ($xmlDoc->getElementsByTagName('item') as $node) {
$item = array(
'title' => $node->getElementsByTagName('title')->item(0)->nodeValue,
'img' => $node->getElementsByTagName('enclosure')->item(0)->attributes['url']->nodeValue
);
echo "<pre>";
var_dump($item);
echo "</pre>";
}

这就是的结果

array(2) {
["title"]=>
string(46) "Kettingbotsing met auto's en vrachtwagen op A2"
["img"]=>
string(10) "image/jpeg"
}

我目前正在获取enclosure标签的类型,但我正在搜索url。

有人能帮我吗,提前感谢

作为使用DOMDocument的替代方案,在这种情况下使用SimpleXML要清楚得多(IMHO(。代码最终为…

$doc = simplexml_load_string($xml_string);
foreach ($doc->item as $node) {
$item = array(
'title' => (string)$node->title,
'img' => (string)$node->enclosure['url']
);
echo "<pre>";
var_dump($item);
echo "</pre>";
}

您需要使用getAttribute()而不是attributes属性

$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')

DOM支持Xpath表达式从XML中获取节点列表和单个值。

$document = new DOMDocument();
$document->loadXML($xml_string);
$xpath = new DOMXpath($document);
// iterate any item node in the document
foreach ($xpath->evaluate('//item') as $itemNode) {
$item = [
// first title child node cast to string
'title' => $xpath->evaluate('string(title)', $itemNode),
// first url attribute of an enclosure child node cast to string
'img' => $xpath->evaluate('string(enclosure/@url)', $itemNode)
];
echo "<pre>";
var_dump($item);
echo "</pre>";
}

像这样简单的东西

$node->enclosure['url']

我想应该有效吗?至少使用simplexmlhttps://www.php.net/manual/en/book.simplexml.php

最新更新