XML:
<?xml version="1.0" encoding="utf-8"?>
<NConfig xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<NDomain>ex1</NDomain>
<Parameters>
<version>p</version>
<siteFolder>site1</siteFolder>
<cssGeneral></cssGeneral>
<cssLogin>l.css</cssLogin>
</Parameters>
<Database>
<hostname>898</hostname>
<username>j</username>
<password>k</password>
<name>n</name>
</Database>
<NDomain>ex2</NDomain>
<Parameters>
<version>p</version>
<siteFolder>site1</siteFolder>
<cssGeneral></cssGeneral>
<cssLogin>l.css</cssLogin>
</Parameters>
<Database>
<hostname>898</hostname>
<username>j</username>
<password>k</password>
<name>n</name>
</Database>
</NConfig>
I would like to itterate through all the nodes under ex1
So far, I can directly access the nodes by doing this:
$xmldata = simplexml_load_file("config.xml");
foreach($xmldata->Parameters as $item)
{
echo "<p>Version: " . $item->version . "</p>";
echo "<p>Site Folder: " . $item->siteFolder . "</p>";
}
But that doesn't make it root node specific, rather it will iterate though all of the parameters in the list. How can I do this?
If your <Parameters>
and <Database>
be specfic for the corresponding <NDomain>
, I prefer you should have ur xml schema like this:
<NDomain>
<name>ex1</name>
<Parameters>
<version>p</version>
<siteFolder>site1</siteFolder>
<cssGeneral></cssGeneral>
<cssLogin>l.css</cssLogin>
</Parameters>
<Database>
<hostname>898</hostname>
<username>j</username>
<password>k</password>
<name>n</name>
</Database>
</NDomain>
<NDomain>
<name>ex2</name>
<Parameters>
<version>p</version>
<siteFolder>site1</siteFolder>
<cssGeneral></cssGeneral>
<cssLogin>l.css</cssLogin>
</Parameters>
<Database>
<hostname>898</hostname>
<username>j</username>
<password>k</password>
<name>n</name>
</Database>
</NDomain>
So you can parse like this :
foreach($xmldata->NDomain as $item)
{
$par = $item->Parameters;
echo "<p>Version: " . $par->version . "</p>";
echo "<p>Site Folder: " . $par->siteFolder . "</p>";
}
You can just iterate over the root nodes children, like this:
$first = true;
foreach($xmldata->children() as $item)
{
if( $first === true) {
$first = false;
continue;
}
}
That loop will catch <NDomain>
, <Parameters>
, and <Database>
, so you'll need a simple check to skip the first iteration to omit <NDomain>
.
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.