Search code examples
xmlsimplexml

XML get Item ID without Foreach


How can I directly call id="url1" without a foreach?

Like this:

echo $item->url1; // Output: http://url1.com

This is code I have:

<?php
$string = <<<XML
<url>
    <item id="url1">http://url1.com/</item>
    <item id="url2">http://url2.com/</item>
</url>
XML;

$xml = simplexml_load_string($string);


foreach($xml->item AS $key => $value){
    echo $value['id'].' = "'.$value.'"<br />';
}
?>

This is the output from the code I have:

url1 = "http://url1.com/"
url2 = "http://url2.com/"

Solution

  • You can query the document using XPath syntax:

    $value = $rules->xpath('item[@id="url1"]')[0];