Loop through an XML with parameters and outputting them as a list?
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>
&开发者_运维技巧lt;/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>
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);
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);
?>
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.'-';
}
}
精彩评论