0

Hello I have an XML code like this:

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

I try to access the parent of an element with SimpleXML like this:

$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>";

}

But I take this result:

Parent element of title: Array

Instead of

Parent element of title: article

What is maybe the problem? Thank you in advance!

4
  • 1
    ->xpath() returns always an array - even if it returns one node only.
    – hakre
    Jul 15, 2012 at 11:46
  • hmmm. Ok. But how can I return the desired result? Jul 15, 2012 at 11:50
  • Try using: name(parent::*) or the equivalent and shorter: name(..) Jul 15, 2012 at 16:02
  • Hello my friend? How to use them? $parent_title = $title....? if you can give me a hand. Thank you anyway! Jul 15, 2012 at 16:56

1 Answer 1

0

Take the first element out of the ->xpath() result array, and call getName() on it. (inside the loop)

$parent_title = $title->xpath("parent::*");
if ($parent_title) {
    echo "Parent element of title: ", $parent_title[0]->getName(), "</br>\n";
}
1
  • It's exactly what I needed! Thanks my friend!! Jul 15, 2012 at 16:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.