无法使用php在其父类别节点下显示xml子节点?

时间:2016-03-09 12:30:19

标签: php xml

我知道我可能会问一个愚蠢的问题,但我非常渴望成为优秀的PHP开发人员,所以无论如何,关于我的问题:

我需要以下结构

  

Cat1 item1 item2
   Cat2 item21 item22
  等....

我的XML结构如下:

<?xml version="1.0" encoding="utf-8"?>
<List>
    <category name="cat1" dispName="First Category" catCode="FC1">
        <item itmCode="item1">
            <name>item 1</name>
            <img>path to image 1</img>
        </item>
        <item itmCode="item2">
            <name>item 2</name>
            <img>path to image 2</img>
        </item>
    </category>
    <category name="cat2" dispName="Second Category" catCode="SC2">
        <item itmCode="item21">
            <name>item 21</name>
            <img>path to image 21</img>
        </item>
        <item itmCode="item22">
            <name>item 22</name>
            <img>path to image 22</img>
        </item>
    </category>
</List>

我的PHP代码如下:

<?php
$xml=simplexml_load_file('items.xml') or die('Error: Cannot create Grouped Items');
foreach($xml->category as $cat){
    $currentCat=$cat['dispName'];
    $catName=$cat['name'];
    echo $catName.'<br/>';
    echo $currentCat.'<br/>';
    $itemsCount=3;
    $random = array_rand($xml->xpath('category'), 3);
    if(is_array($random) || is_object($random)){
        foreach ($random as $key){
            //here is the issue as am trying to get the child nodes of each of the category nodes from the above XML list
        }
    }else{echo '<br/>error<br/>';}
}
?>

什么是写一个好的高性能列表页面的最佳方式,我将在后面有太多的类别,每个类别将有超过30个项目。

我真的很感激任何帮助和建议真的很感激,因为我独自在这个项目(一个家庭项目)工作,开发人员 - 设计师:)

1 个答案:

答案 0 :(得分:1)

如果项目按类别分组,就像在示例XML中一样,两个简单的foreach循环可以解决这个问题:

$xml = simplexml_load_string($x); // assume XML in $x

foreach ($xml->category as $cat) {
    echo $cat['dispName'] . PHP_EOL;
    foreach ($cat->item as $item) {
        echo $item->name . PHP_EOL;
    }
}

添加计数器以限制项目,如果counter = limit,则使用break停止内部foreach循环。

foreach ($xml->category as $cat) {
    echo $cat['dispName'] . PHP_EOL;
    $count = 0;
    foreach ($cat->item as $item) {
        echo $item->name . PHP_EOL;
        $count = $count + 1;
        if ($count == 3) break; 
    }
}

作为替代方案,只有当计数器<&lt;时,才能echo该项目。限制,但循环将继续到类别中的最后一项,如果你有大量的项目,这将降低性能。

查看实际操作:https://eval.in/533305