Thursday, September 1, 2022

[SOLVED] Get the URL tag from enclosure XML

Issue

I want to get the URL from the enclosure tag with PHP

This is what i get from the RRS feed

<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>

This is the code im using now

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

And this is the result

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

I'm currently getting the type of the enclosure tag, but i'm searching for the url.

Can someone help me, Thanks in advance


Solution

You need to use getAttribute() instead of attributes property

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


Answered By - Mohammad
Answer Checked By - Dawn Plyler (WPSolving Volunteer)