【问题标题】:Get the URL tag from enclosure XML从附件 XML 中获取 URL 标记
【发布时间】:2019-04-23 19:40:57
【问题描述】:

我想用 PHP 从附件标签中获取 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"
}

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

谁能帮帮我, 提前致谢

【问题讨论】:

标签: php xml curl dom


【解决方案1】:

作为使用 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>";
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • @StanvanHeertum 很高兴为您提供帮助
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2015-02-26
      • 1970-01-01
      • 2015-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多