PHP:使用单纯级循环遍历XML文件的所有级别
题
我有一个函数,该函数使用单纯词返回XML文件中的第一个节点,然后将其写入无序列表:
function printAssetMap() {
$xml = simplexml_load_file(X_ASSETS);
$assets = $xml->asset;
$html = '<ul>'."\n";
foreach ($assets as $asset) {
$html .= '<li id="asset'.$asset->asset_assetid.'"><ins> </ins><a href="#">'.$asset->asset_name.' ['.$asset->asset_assetid.']</a></li>'."\n";
}//end foreach
$html .= '</ul>'."\n";
return $html;
}// printAssetMap()
我正在使用的XML,该节点嵌套了:
<?xml version="1.0"?>
<assets>
<asset>
<asset_name>Home</asset_name>
<asset_url>/home</asset_url>
<asset_assetid>1</asset_assetid>
</asset>
<asset>
<asset_name>Projects</asset_name>
<asset_url>/projects</asset_url>
<asset_assetid>2</asset_assetid>
<asset>
<asset_name>Portfolio</asset_name>
<asset_url>/projects/portfolio</asset_url>
<asset_assetid>3</asset_assetid>
</asset>
<asset>
<asset_name>Current Jobs</asset_name>
<asset_url>/projects/current-jobs</asset_url>
<asset_assetid>4</asset_assetid>
</asset>
</asset>
</assets>
现在,我开始添加我目前要返回的节点的子节点。是否有一种方法可以在XML文件中循环浏览所有级别的子节点,即使我不知道有多少级别并将其添加到我的列表中?
解决方案
因此,基本上您需要做的是一个占用每个功能 <asset/>
当前节点的孩子,构建HTML,然后检查当前节点是否具有 <asset/>
自己的孩子,并保持更深的沿树的深处。
您可以做到这一点:
function printAssetMap()
{
return printAssets(simplexml_load_file(X_ASSETS));
}
function printAssets(SimpleXMLElement $parent)
{
$html = "<ul>\n";
foreach ($parent->asset as $asset)
{
$html .= printAsset($asset);
}
$html .= "</ul>\n";
return $html;
}
function printAsset(SimpleXMLElement $asset)
{
$html = '<li id="asset'.$asset->asset_assetid.'"><ins> </ins><a href="#">'.$asset->asset_name.' ['.$asset->asset_assetid.']</a>';
if (isset($asset->asset))
{
// has <asset/> children
$html .= printAssets($asset);
}
$html .= "</li>\n";
return $html;
}
顺便说一下,我希望一个名为“ printx”的功能实际上 打印 或回声某物,而不是返回。也许您应该将这些功能命名为“ buildx”?
其他提示
您需要使用递归功能。这是一个从XML输出数组的示例。它来自PHP文档 - http://www.php.net/manual/en/ref.simplexml.php. 。您可以对此进行修改以输出列表。
<?php
function XMLToArray($xml)
{
if ($xml instanceof SimpleXMLElement) {
$children = $xml->children();
$return = null;
}
foreach ($children as $element => $value) {
if ($value instanceof SimpleXMLElement) {
$values = (array)$value->children();
if (count($values) > 0) {
$return[$element] = XMLToArray($value);
} else {
if (!isset($return[$element])) {
$return[$element] = (string)$value;
} else {
if (!is_array($return[$element])) {
$return[$element] = array($return[$element], (string)$value);
} else {
$return[$element][] = (string)$value;
}
}
}
}
}
if (is_array($return)) {
return $return;
} else {
return $false;
}
}
?>
<?php
function all_nodes($xml){
$all=array();
function add($node){
array_push($all,$node);
foreach($node as $child){
add($child);
}
}
add($xml->documentElement);
return $all;
}
?>
这将返回文档中所有节点的数组。
不隶属于 StackOverflow