我想使用PHP从附件标签中获取URL
这是我从RRS供稿中获得的
<item>
<title>Kettingbotsing met auto's en vrachtwagen op A2</title>
<link>https://www.1limburg.nl/kettingbotsing-met-autos-en-vrachtwagen-op-a2</link>
<description><p>Drie auto&#39;s en een vrachtauto zijn woensdagochtend met elkaar gebotst op de A2.&nbsp;&nbsp;</p></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"
}
我目前正在获取附件标签的类型,但是我正在搜索网址。
有人可以帮我吗, 预先感谢
答案 0 :(得分:1)
您需要使用getAttribute()
而不是attributes
属性
$node->getElementsByTagName('enclosure')->item(0)->getAttribute('url')
答案 1 :(得分:0)
作为使用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>";
}
答案 2 :(得分:0)
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>";
}