curl 从附件XML中获取URL标记

myss37ts  于 2022-11-13  发布在  其他
关注(0)|答案(4)|浏览(146)

我想用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。
有人能帮我吗,先谢谢

polhcujo

polhcujo1#

作为使用DOMDocument的一种替代方法,在这种情况下使用SimpleXML要清楚得多(恕我直言)。

$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>";
}
voase2hg

voase2hg2#

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

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

dzjeubhm3#

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>";
}
whlutmcx

whlutmcx4#

一些简单的东西

$node->enclosure['url']

我想应该可以工作吧?至少用simplexmlhttps://www.php.net/manual/en/book.simplexml.php可以

相关问题