1

I have an XML file and the data is passed through parameters, like so:

<node id="a" title="Title A">
    <node id="b"  title="Title B">
       <node id="c"  title="Title C">
       </node>
    </node>
    <node id="d"  title="Title D">
    </node>
</node>

How can I loop recursively through this XML and print only the ID of every node in a list? i.e.

<ul>
   <li>a</li>
   <ul>
      <li>b</li>
      <ul>
         <li>c</li>
      </ul>
   </ul>
   <ul>
      <li>d</li>
   </ul>
</ul>

3 Answers 3

0

Although it would be possible without xslt, I think this is more reusable:

<?php
$dom = new DOMDocument();
$dom->loadXml('<node id="a" title="Title A">
    <node id="b"  title="Title B">
       <node id="c"  title="Title C">
       </node>
    </node>
    <node id="d"  title="Title D">
    </node>
</node>');


$xsl = new DOMDocument;
$xsl->loadXml('<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="/">
        <ul><xsl:apply-templates /></ul>
    </xsl:template>

    <xsl:template match="node">
        <li><xsl:value-of select="@title" /> (<xsl:value-of select="@id" />)
            <xsl:if test="count(descendant::node) > 0">
                <ul><xsl:apply-templates /></ul>
            </xsl:if>
        </li>
    </xsl:template>
</xsl:stylesheet>', LIBXML_NOCDATA);

$xslt = new XSLTProcessor();
$xslt->importStylesheet($xsl);

echo $xslt->transformToXML($dom);
0

If you need to have access to the nodes before printing you can do it by using simplexml_load_string:

<?php

$str = '<node id="a" title="Title A">
    <node id="b"  title="Title B">
       <node id="c"  title="Title C">
       </node>
    </node>
    <node id="d"  title="Title D">
    </node>
</node>';

$xml = simplexml_load_string($str);

print_r($xml);
?>
0

To access the child nodes

$xml = simplexml_load_file('test.xml');
var_dump($xml);

foreach($xml as $node){
    foreach($node->attributes() as $key=>$val){

        echo $key.'-'.$val.'-';
    }
}

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.