高分在线求助XML解析
本帖最后由 HUENKE 于 2013-10-25 15:58:22 编辑
<?xml version="1.0" encoding="utf-8"?>
<nodes>
<node id="c5569e2c-0f4a-4ec2-86ba-736b79eca18c" name="A公司"
type="0">
<node id="4f2b55e9-e10a-496b-8bca-60e6f26daee5" name="部门1" type="1">
<node id="363" name="叶子1" type="2" playurl="http://XXXXXXX363" />
</node>
<node id="0c5ce42f-ba31-4b7a-8173-79ecae4a73ca" name="部门2" type="1">
<node id="241" name="叶子1" type="2"playurl="http://xxxxx=241" />
<node id="356" name="叶子1" type="2" playurl="xxxxxxxxx=356" />
</node>
</node>
</nodes>
<?php
$string = <<<XML
<?xml version="1.0" encoding="utf-8"?>
<nodes>
<node id="c5569e2c-0f4a-4ec2-86ba-736b79eca18c" name="A公司"
type="0">
<node id="4f2b55e9-e10a-496b-8bca-60e6f26daee5" name="部门1" type="1">
<node id="363" name="叶子1" type="2" playurl="http://XXXXXXX363" />
</node>
<node id="0c5ce42f-ba31-4b7a-8173-79ecae4a73ca" name="部门2" type="1">
<node id="241" name="叶子1" type="2" playurl="http://xxxxx=241" />
<node id="356" name="叶子1" type="2" playurl="xxxxxxxxx=356" />
</node>
</node>
</nodes>
XML;
$xml = new SimpleXMLElement($string);
$result = $xml->xpath('//node/@name');
while(list( , $node) = each($result)) {
echo '@name: ',$node,"\n";
}
$result = $xml->xpath('//node/@id');
while(list( , $node) = each($result)) {
echo '@id: ',$node,"\n";
}
$result = $xml->xpath('//node[@type=1]/../@id');
while(list( , $node) = each($result)) {
echo '@部门的parent_id: ',$node,"\n";
}
$result = $xml->xpath('//node[@type=2]/../@id');
while(list( , $node) = each($result)) {
echo '@叶子的parent_id: ',$node,"\n";
}
?>
$s =<<< XMLid => c5569e2c-0f4a-4ec2-86ba-736b79eca18c
<?xml version="1.0" encoding="utf-8"?>
<nodes>
<node id="c5569e2c-0f4a-4ec2-86ba-736b79eca18c" name="A公司"
type="0">
<node id="4f2b55e9-e10a-496b-8bca-60e6f26daee5" name="部门1" type="1">
<node id="363" name="叶子1" type="2" playurl="http://XXXXXXX363" />
</node>
<node id="0c5ce42f-ba31-4b7a-8173-79ecae4a73ca" name="部门2" type="1">
<node id="241" name="叶子1" type="2" playurl="http://xxxxx=241" />
<node id="356" name="叶子1" type="2" playurl="xxxxxxxxx=356" />
</node>
</node>
</nodes>
XML;
$xml = simplexml_load_string($s);
foreach($xml->node as $node) {
foreach($node->attributes() as $k=>$v) echo "$k => $v\n";
foreach($node->node as $node) {
foreach($node->attributes() as $k=>$v) echo "$k => $v\n";
foreach($node->node as $node) {
foreach($node->attributes() as $k=>$v) echo "$k => $v\n";
}
}
}