访问SimpleXML元素的父元素会导致“Array”

时间:2012-07-15 11:42:00

标签: php xpath simplexml

您好我有这样的XML代码:

<article>
  <title><![CDATA[IEEE Transactions on]]></title>
  <articleinfo>
    <articleseqnum>13</articleseqnum>
    <idamsid>0b0000648011bcfb</idamsid>
.............

我尝试使用SimpleXML访问元素的父元素,如下所示:

$xmlUrl = "example.xml"; // XML feed file/URL

$xmlStr = file_get_contents($xmlUrl);

$xmlObj = simplexml_load_string($xmlStr);

$titles = $xmlObj->xpath("//title");

foreach ($titles as $title)
{
   $parent_title = $title->xpath("parent::*");

   echo "Parent element of title: ". $parent_title."</br>";

}

但我接受了这个结果:

Parent element of title: Array

而不是

Parent element of title: article

可能是什么问题?提前谢谢!

1 个答案:

答案 0 :(得分:0)

从 - &gt; xpath()结果数组中取出第一个元素,并在其上调用getName()。 (在循环内)

$parent_title = $title->xpath("parent::*");
if ($parent_title) {
    echo "Parent element of title: ", $parent_title[0]->getName(), "</br>\n";
}