显示xml中的所有节点

时间:2014-02-18 08:52:00

标签: php xml simplexml

这是我的xml结构:

<?xml version="1.0"?>
    <Module_Files>
        <Category name="test1">
            <file lang="fr">
                <title>Menu</title>
                <description>Menu list</description>
                <path>menu.pdf</path>
            </file>
        </Category>
        <Category name="test2">
            <file lang="fr">
                <title>Spa</title>
                <description>Services offered in our Spa</description>
                <path>spa.pdf</path>
            </file>
            <file lang="en">
                <title>Gym</title>
                <description>rate</description>
                <path>gym.pdf</path>
            </file>

        </Category>
    </Module_Files>

我想为每个类别<Category>获取所有文件<file>。但我只设法获得第一个文件。我希望像这样显示(我为示例选择test2类别):

  

标题:水疗中心,描述:我们水疗中心提供的服务,路径:spa.pdf

     

标题:健身房,描述:率,路径:gym.pdf

这是我的代码:

 $categoryConfig = $xmlFile->xpath("//Category[@name='" . $categorySelected . "']/config");

 foreach ($categoryConfig as $key => $value) 
 {  
    $rightPanel .= $key . ":" . $value;   
 }

这就是我用这段代码得到的:

  

0:1:

var_dump($categoryConfig) =

array(2) { 
    [0]=> object(SimpleXMLElement)#26 (4) 
        { ["@attributes"]=> array(1) { ["lang"]=> string(2) "fr" } 
        ["title"]=> string(3) "Spa" ["description"]=> string(35) "Services offered in our Spa" ["path"]=> string(7) "spa.pdf" } 

    [1]=> object(SimpleXMLElement)#27 (4) 
        { ["@attributes"]=> array(1) { ["lang"]=> string(2) "en" } 
        ["title"]=> string(14) "Gym" ["description"]=> string(29) "Rate" ["path"]=> string(18) "gym.pdf" } 
    }

1 个答案:

答案 0 :(得分:0)

使用children()方法的嵌套循环将执行此操作:

$xml = simplexml_load_string($x); // assume XML in $x

$catname = "test2";
// select all <file> under <category name='test2'>
$files = $xml->xpath("/*/Category[@name='$catname']/file");

foreach ($files as $file) {
    foreach ($file->children() as $key => $value) 
        echo $key . ': ' . $value . PHP_EOL;
    echo PHP_EOL;
}        

正如ThW的评论指出的那样,你的xpath表达式不匹配,因为xml中没有<config>。我在这里将其调整为<file>

看到它有效:https://eval.in/102766

相关问题