【问题标题】:Can't show xml child nodes under their parent category node using php?无法使用 php 在其父类别节点下显示 xml 子节点?
【发布时间】:2016-03-09 12:30:19
【问题描述】:

我知道我可能问了一个愚蠢的问题,但我真的很渴望优秀的 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 个项目。

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

【问题讨论】:

  • 请指定您想要完成的任务。您的代码似乎过于复杂,无法解决您在上面描述的问题。
  • 我只需要列出每个类别中的 x 个项目,并将类别名称写在其项目的顶部。
  • 欲了解更多信息,我有一个正在运行的页面,其中包含我需要查看的内容,但其行为不当目前 uistarter.com/css3icons/icons.php 目前正在拥有该类别,我想要在每只猫下方列出 3 个项目

标签: php xml


【解决方案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 来限制项目,如果 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; 
    }
}

作为替代方案,您可以 echo 仅当 counter

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

【讨论】:

  • 非常感谢您的帮助,如果适用,我还有一个小问题,我想随机获得 3 件物品,可以完成吗??
  • 我想出了如何每次获得3个随机项目:$icons=array();foreach($cat-&gt;icon as $icon){$icons[] = $case;}shuffle($icons);
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多