如何从此xml对象中提取值?

时间:2011-01-14 20:04:40

标签: php xml simplexml

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/" 
      } 

我想使用php从xml以上提取titleabstract的值。

5 个答案:

答案 0 :(得分:1)

您已经使用SimpleXML解析了它,您真正想要做的是遍历您的对象并找到titleabstract的值。

如果您的对象为$xml,则$xml->resultset_web->result[0]->abstract包含abstract $xml->resultset_web->result[0]->title包含title一个值。对于所有值,

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

答案 1 :(得分:1)

通过判断,我可以看到你有大约10个标题要提取:

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

这样做的方法是:

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

答案 2 :(得分:1)

这看起来像是包含SimpleXML对象的var的var_dump。 所以,让我们说你有这样的事情:

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

然后你应该能够访问这样的项目:

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

答案 3 :(得分:0)

如果要获取所有带路径的节点resultset_web - >结果 - >标题:

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

答案 4 :(得分:0)

未经测试,但应该有效:

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

如上所述,只需阅读php simplexml文档。请注意,并非每个案例都这么简单,如果您有多个结果,您将不得不使用children()方法遍历子项,您不能像我上面那样直接访问它们。