簡體   English   中英

顯示xml中的所有節點

[英]Display all nodes in a xml

這是我的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 Category為例):

標題:水療中心,描述:我們水療中心提供的服務,路徑: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" } 
    }

使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM