LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   How to traverse through the XML nodes? (http://www.linuxquestions.org/questions/programming-9/how-to-traverse-through-the-xml-nodes-891225/)

gozlemci 07-12-2011 01:52 AM

How to traverse through the XML nodes?
 
Dear friends of linuxquestions.org;
I'm struggling with a very irritating problem:
I have a xml file and I read it within a php file with XML dom.

This is the node structure of my xml file :
<Root>
<name></name>
<surname></surname>
<ID></ID>
<department></department>
<rank></rank>
<telNo></telNo>
<deckNo></deckNo>
<mobileNo secrecy="c"></mobileNo>
<homeTelNo secrecy="c"></homeTelNo>
</Root>

Here are the php code of mine:

Code:

$in_name = $_POST["name"];
$in_surname = $_POST["surname"];
$in_department = $_POST["department"];
 
$doc = new DOMDocument();
$doc->load('http://localhost/xampp/tsbs_yellow_pages/run/1/databank.xml');
$xPath = new DOMXPath($doc);

if($in_name != '')
        {
                $nodeList = $xPath->query('//User/name');
                $phase = trim(($in_name));
                $length_of_phase = strlen($phase);
}

        foreach($nodeList as $node)
        {
                if(  strncasecmp( trim($node->nodeValue),$phase,$length_of_phase) == 0)
                {                       
                 
                        $parent_nodes = $node->parentNode;
                        //Here is the point
                        for($i = 1; $i <= 4; $i++)
                        {
                                echo("<p>$parent_nodes->nodeValues</p>\n");
                        }
                       

                }
               
        }

In the comment line, I've got the parent node of the current node. Parent node is "User" node. I would like to obtain the children of this parent node, say "name","surname " etc. How can I do this? Is there any function such as : "$parent_nodes->bringChildren('name')". I could not find it.

Thanks in advance.

paulsm4 07-12-2011 01:25 PM

Hi -

This is a great tutorial:

http://www.ibm.com/developerworks/xm...ary/x-xmlphp1/

http://www.ibm.com/developerworks/xm...ary/x-xmlphp2/

http://www.ibm.com/developerworks/xm...ary/x-xmlphp3/

From Chap 2, I believe this answers your question:
Code:

xpath = new DOMXPath($doc);

// We start from the root element
$query = '//book/chapter/para/informaltable/tgroup/tbody/row/entry[. = "en"]';

$entries = $xpath->query($query);

foreach ($entries as $entry) {
  echo "Found {$entry->previousSibling->previousSibling->nodeValue}," .
        " by {$entry->previousSibling->nodeValue}\n";
}

'Hope that helps .. PSM


All times are GMT -5. The time now is 12:06 PM.