English 中文(简体)
PHP: Using simplexml to loop through all levels of an XML file
原标题:

I have a function which uses simplexml to return the first level of nodes in an XML file and write it into an unordered list:

function printAssetMap() {
    $xml = simplexml_load_file(X_ASSETS);
    $assets = $xml->asset;
    $html =  <ul> ."
";
    foreach ($assets as $asset) {
        $html .=  <li id="asset .$asset->asset_assetid. "><ins>&nbsp;</ins><a href="#"> .$asset->asset_name.  [ .$asset->asset_assetid. ]</a></li> ."
";
    }//end foreach
    $html .=  </ul> ."
";
    return $html;
}// printAssetMap()

XML I am using, that has nested nodes:

<?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>

Now, I am starting to add child nodes of the nodes that I am currently returning. Is there a way to loop through ALL levels of child nodes in an xml file, even if I don t know how many levels there are, and add those to my list?

最佳回答

So basically what you need to do is a function that takes each <asset/> child of current node, builds the HTML then checks if the current node has <asset/> children of its own and keeps recursing deeper down the tree.

Here s how you can do it:

function printAssetMap()
{
    return printAssets(simplexml_load_file(X_ASSETS));
}

function printAssets(SimpleXMLElement $parent)
{
    $html = "<ul>
";
    foreach ($parent->asset as $asset)
    {
        $html .= printAsset($asset);
    }
    $html .= "</ul>
";

    return $html;
}

function printAsset(SimpleXMLElement $asset)
{
    $html =  <li id="asset .$asset->asset_assetid. "><ins>&nbsp;</ins><a href="#"> .$asset->asset_name.  [ .$asset->asset_assetid. ]</a> ;

    if (isset($asset->asset))
    {
        // has <asset/> children
        $html .= printAssets($asset);
    }

    $html .= "</li>
";

    return $html;
}

By the way, I would expect a function named "printX" to actually print or echo something, rather than return it. Perhaps you should name those functions "buildX" ?

问题回答

you need to use a recursive function. here is an example that outputs an array from XML. It is from the PHP docs - http://www.php.net/manual/en/ref.simplexml.php. You can amend this to output a list.

<?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;
}
?>

This will return an array with all nodes in the document.





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签