PHP: Using simplexml to loop through all levels of an XML file

后端 未结 3 527
野的像风
野的像风 2021-01-03 05:16

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() {
             


        
3条回答
  •  时光说笑
    2021-01-03 06:00

    So basically what you need to do is a function that takes each child of current node, builds the HTML then checks if the current node has 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 = "
      \n"; foreach ($parent->asset as $asset) { $html .= printAsset($asset); } $html .= "
    \n"; return $html; } function printAsset(SimpleXMLElement $asset) { $html = '
  •  '.$asset->asset_name.' ['.$asset->asset_assetid.']'; if (isset($asset->asset)) { // has children $html .= printAssets($asset); } $html .= "
  • \n"; 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" ?

提交回复
热议问题