This is my xml structure:
<?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>
I want to get for each category <Category>
all files <file>
. but I only managed to get the first file. I want to display like this (I take test2 Category for the example):
title : Spa, description : Services offered in our Spa, path: spa.pdf
title : Gym, description : rate, path : gym.pdf
This is my code :
$categoryConfig = $xmlFile->xpath("//Category[@name='" . $categorySelected . "']/config");
foreach ($categoryConfig as $key => $value)
{
$rightPanel .= $key . ":" . $value;
}
And this is what I get with this code:
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" }
}
Nested loops with the children()
-method will do it:
$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;
}
As ThW's comment points out, your xpath
expression does not match, as there is no <config>
in the xml. I adjusted it to <file>
here.
see it working: https://eval.in/102766
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.