开发者

How do I extract values from this xml object?

object(SimpleXMLElement)#1 (3) { 
["@attributes"]=> array(1) { 
   ["responsecode"]=> string(3) "200" 
} 
["nextpage"]=> object(SimpleXMLElement)#2 (0) { 
} 
["resultset_web"]=> object(SimpleXMLElement)#3 (2) { 
   ["@attributes"]=> array(4) { 
      ["count"]=> string(2) "10" 
      ["start"]=> string(1) "0" 
      ["totalhits"]=> string(8) "22497060" 
      ["deephits"开发者_运维技巧]=> string(8) "23000000" 
   } 
   ["result"]=> array(10) { 
      [0]=> object(SimpleXMLElement)#4 (7) { 
         ["abstract"]=> string(110) "MSN's all-in-one Internet portal, the home of Hotmail, MSN Messenger, MSNBC News, Encarta, and Slate Magazine." 
         ["clickurl"]=> string(360) "http://teqpad.com/www/msn.com" 
         ["date"]=> string(10) "2011/01/14" 
         ["dispurl"]=> object(SimpleXMLElement)#14 (0) { 
         } 
         ["size"]=> string(5) "82136" 
         ["title"]=> string(3) "MSN" 
         ["url"]=> string(19) "http://www.msn.com/" 
      } 

I want to extract value of title and abstract from above xml using php.


You have already parsed it with SimpleXML, what you really want to do is traverse through your object and find the values of title and abstract.

If your object is $xml, $xml->resultset_web->result[0]->abstract contains abstract while
$xml->resultset_web->result[0]->title contains title for one value. For all the values,

foreach ($xml->resultset_web->result as $v) {
  $title = $v->title;
  $abstract = $v->title;
}


I can see that you have about 10 titles to extract by judging from this:

["result"]=> array(10) { 

The way of doing this would be:

foreach ($simpleXML->resultset_web->result as $result) {
    $title = $result->title;
    $abstract = $result->abstract;
}


That looks like a var_dump of a var that holds a SimpleXML object. So let's say that you have something like this:

//$data i a string containing your XML
$xmlobj = new SimpleXMLElement($data);

then you should be able to access the items like this:

foreach ($xmlobj->resultset_web->result as $result) {
    echo $result->abstract;
    echo $result->title;
}


If you want to get all nodes with path resultset_web -> result -> title:

$xml = [your object];
$allTitlesAsArray = $xml->xpath('/resultset_web/result/title');
$allAbstractAsArray = $xml->xpath('/resultset_web/result/abstract');


Untested, but should work :

$ob->resultset_web->result[0]->title;

As said, just read up on the php simplexml documentation. And note that not each case will be this simple, if you have multiple results you will have to iterate through the children with the children() method, you can't access them directly as I did above.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜