SimpleXMLElement
不是那么简单,实际上它得到简单只有当你猜如何处理呢?或者有人跟你。
假设regions.xml
是这样的:
<regions>
<region id="01" size="big">
New Zealand
</region>
<region id="02" size="small">
Tokelau
</region>
</regions>
下面的PHP代码可以导航通过XML文档:
$xml = new SimpleXMLElement('regions.xml');
foreach ($xml->region as $region) { // iterate through all the regions
echo 'Region ID: '. (string)$region['id']; // get the attribute id
echo 'Region size: '. (string)$region['size']; // get the attribute size
echo 'Region name: '. (string)$region; // get the contents of the
// element by casting it to a string
}
现在让我们做的东西有点困难......假设<region>
有一个子元素,<subregion>
。
<regions>
<region id="01" size="big">
<name>USA</name>
<subregion id="01_1">Alaska</subregion>
</region>
...
</regions>
如果你想获得每个地区所有次区域,你必须这样做:
$xml = new SimpleXMLElement('regions.xml');
foreach ($xml->region as $region) { // iterate through all the regions
foreach ($region->subregion as $subregion) // iterate trough the subregion of $region
// do something
}
}
您的文档结构似乎比这更复杂一点,但使用这些基本知识,你可以轻松解决。
来源
2012-09-21 18:00:19
gd1
[基本的SimpleXML用法](http://php.net/manual/en/simplexml.examples-basic。 PHP) – Gordon