0

My XML

<properties>
<property>
    <refno>001</refno>
    <status>active</status>
    <type>SP</type>
    <description>Text Text Text</description>
    <images>
      <image>Path_here</image>
      <image>Path_here</image>
      <image>Path_here</image>
    </images>
</property>
<property>
    <refno>002</refno>
    <status>active</status>
    <type>SP</type>
    <description>Text Text Text</description>
     <images>
      <image>Path_here</image>
      <image>Path_here</image>
      <image>Path_here</image>
    </images>
</property>
</properties>

My PHP Code

if ($xml = simplexml_load_file($xml_file_here)) {
    foreach($xml->property as $i) {
        if ($i->refno == "1") {
            echo $i->description."<br />".
            echo $i->type;
        }
    }
}

I normally loop though the XML to find a [refno] value. Is there a way to search for value without the need to loop?

Mike'78
  • 51
  • 6
  • You could wrap this logic into a function to return the element that matches, but this is the correct way already. – scrowler Jun 10 '14 at 01:43
  • even if im looping for thousands of nodes? Is there any other better and faster way? it makes the script execution slow. – Mike'78 Jun 10 '14 at 01:48
  • What about a `if(strpos($your_xml_text, '12345') !== false) { // do stuff }` call over your XML **text** to quickly determine whether or not the element exists, then if it does you loop until you find it? – scrowler Jun 10 '14 at 01:49
  • Do you just need the specific node(s), or the node(s) and it/their full hierarchy? – Sheepy Jun 10 '14 at 02:04
  • I need to get the siblings (status, type, description, images) of the matched – Mike'78 Jun 10 '14 at 02:16

1 Answers1

1

You can make use of an XPath expression:

// find property element that contains a refno element with "001"
foreach ($xml->xpath('//property[contains(refno, "001")]') as $node) {
    echo (string)$node->description, "\n";
}
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • is unique, no duplicates – Mike'78 Jun 10 '14 at 02:26
  • @Ratbucoh Well, `xpath()` returns an array of found elements; feel free to just pick the first one and skip the `foreach`. – Ja͢ck Jun 10 '14 at 02:55
  • @Ratbucoh since `refno` is unique, just assign it on a variable `$values = $xml->xpath('//property[contains(refno, "001")]'); $values = reset($values);` you got yourself the values. this already the correct answer – user1978142 Jun 10 '14 at 03:04