how to retrieve particular node.. i.e., if b node had value like <b id="1"> means it will return b's child nodes..
output must be:
<c>text</c>
<c>stuff</c>

Here is my code:

<?php
$string = <<<XML
<a>
<b>
<c>text</c>
<c>stuff</c>
</b>
<b id="1">
<c>code</c>
</b>
<d>
<c>item</c>
</d>
</a>
XML;
$xml = new SimpleXMLElement($string);
 $xml->asXML()."<br>";
   // echo "<c>".(string)$child."</c>";
    foreach( $xml->children() AS $child )
{
    //run any query you want on the children.. they are also nodes.
   $name1 = $child;
  //echo "<pre><c></pre>".$name1."<pre><c></pre><br>";
   foreach( $name1->children() AS $child1 )
{
     $name2 = $child1->getName();
     $child2=$child1;
    // echo $name2."--".$child2;
    //if($child2=="code")
        //foreach($child1->query('//b[@name="title"]') as $child2)

        echo "<".$name2.">".$child2."<⁄".$name2.">"."<br>";

}
}
?>

Recommended Answers

All 3 Replies

Member Avatar for diafol

From the manual: http://www.php.net//manual/en/class.domxpath.php

You could try something like this...

function getChildXML($xml, $tag, $id)
{
    $output = '';
    $doc = new DOMDocument();
    $doc->loadXML($xml);
    $xpath = new DOMXpath($doc);
    $elements = $xpath->query($tag . "[@id='$id']");
    foreach($elements as $element)
        $output .= $doc->saveXML($element);
    return $output;
}


print getChildXML($string, 'b', 1);

Which gives the output...

<b id="1">
<c>code</c>
</b>

Obviously you could develop the function to deal with 'no id' values etc.

For me it display's something like this.
output:
text stuff..
But i need <c>text</c>
<c>stuff</c>

thank you so much.. got it.. but don want <b id="1"> jus wanna display child nodes..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.