php - Getting an xml element value using xpath -
i'm parsing xml results google xml search results feed , i'm struggling image value within 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 current loop
foreach ($xml->res->r $item) { $image = $item->pagemap->dataobject[4]->attribute[2]['value']; } the problem image i'm trying grab isn't in 4th dataobject. xml search results feed can have either 1 or several dataobject elements.
so i've done little reading find xpath give me abbility target right dataobject width attribute of type , value of cse_thumbnail, regardless of how many dataojects exist within parent element (<pagemap>).
this stuck.
foreach ($xml->res->r $item) { $image = $item->pagemap->xpath('dataobject[@type="cse_thumbnail"]/attribute[@name="src"]/@value'); } the $image variable returns array. thought homecoming value <attribute> 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 shed lite on doing wrong
thanks
your xpath correct, can check online, example: http://www.xpathtester.com/xpath
but pagemap returns array, check thread here possible solutions: php xpath extracting value node attribute name="author"
something like:
foreach ($xml->res->r $item) { $images = $item->pagemap->xpath('dataobject[@type="cse_thumbnail"]/attribute[@name="src"]/@value'); if (count($images)) { $image = (string) $images[0]['value']; } } php xml for-loop xpath google-cse
No comments:
Post a Comment