Search code examples
phpxmlfor-loopxpathgoogle-custom-search

Getting an xml element value using xpath


I'm parsing xml results from a google xml search results feed and I'm struggling to get the image value from within a specific DataObject element

<DataObject type="cse_thumbnail">
    <Attribute name="width" value="395"/>
    <Attribute name="height" value="127"/>
    <Attribute name="src" value="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTZMcIvtnauaF5yVIAcxEsJgj-r78xsi32b18X5tuMamDZIVWNBTXoB-g"/>
</DataObject>

This is my current loop

foreach ($xml->RES->R as $item) {
   $image = $item->PageMap->DataObject[4]->Attribute[2]['value'];
}

The problem I get is the image I'm trying to grab isn't always in the 4th DataObject. The xml search results feed can have either just one or several DataObject elements.

So i've done a little reading to find that xpath will give me the abbility to target the correct DataObject width the attribute of type and the value of cse_thumbnail, regardless of how many DataOjects exist within a parent element (<PageMap>).

This is where I get stuck.

foreach ($xml->RES->R as $item) {
          $image = $item->PageMap->xpath('DataObject[@type="cse_thumbnail"]/Attribute[@name="src"]/@value');

}

The $image variable returns as an Array. I thought it would return the value from the <Attribute> where name="src".

array(1) { [0]=> object(SimpleXMLElement)#14 (1) { ["@attributes"]=> array(1) { ["value"]=> string(110) "https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTZMcIvtnauaF5yVIAcxEsJgj-r78xsi32b18X5tuMamDZIVWNBTXoB-g" } } }

Can anyone shed any light on what I am doing wrong

Thanks


Solution

  • Your xPath is correct, you can check it online, for example: http://www.xpathtester.com/xpath

    But the PageMap returns an array, check this thread here for possible solutions: PHP Xpath extracting a value for a node with attribute name="author"

    Something like:

    foreach ($xml->RES->R as $item) {    
       $images = $item->PageMap->xpath('DataObject[@type="cse_thumbnail"]/Attribute[@name="src"]/@value');    
       if (count($images)) {
           $image = (string) $images[0]['value'];    
       }    
    }