【问题标题】:php - simpleXML put same nodes into arrayphp - simpleXML 将相同的节点放入数组中
【发布时间】:2011-11-11 12:16:25
【问题描述】:

我正在使用 PHP 的简单 xml 读取 XML 文件。 I 循环遍历每个类别节点以根据已选择的类别显示包含节点的数据,从而显示子类别。我需要以某种方式检测一个类别何时没有子类别。我需要的是可能将所有 parent_id 节点放入一个数组中,然后查看 cat_id 是否在数组中以检测它是否有任何依赖项。

$cat_xml = simplexml_load_file(XML_PATH.'categories/'. $clientID . '.xml');

            //get all the categories and go through each one
            foreach($cat_xml as $cat){  
                if ( //WHAT GOES HERE?? ){
                    //display if cat is top level or has been selected 
                    if ($cat->parentID == $cat_parent_id){
                        //check product isn't set to hidden
                        if ($cat->visible == 1){
                            echo '<div class="catbox">';
                                echo "<a href=\"index.php?pageID=$pageID&cat_parent_id=$cat->id&cat_name=$cat->Name\"> $cat->Name </a><br />";
                            echo '</div>';
                        }
                    }
                } else {
                    echo '<p>There are no sub categories.</p>';
                }
            }

[编辑]
XML 在下面,我需要获取一组“parentID”值

<categories> <category> <id>740073</id> <Name>Leetee Cat 1</Name> <parentID>0</parentID> <Description><![CDATA[Charlotte Balbier Weddinhg <em>dresses</em>,<strong> blah blah blah!!<br /> </strong>]]></Description> <imageURL>alice-charlotte-balbier-english-tea-party-collection-2011.jpg</imageURL> <sequence>0</sequence> <visible>1</visible> </category>

【问题讨论】:

  • 请显示 XML 的 sn-p 并说明您需要从中解析什么。
  • 我已将 XMl 添加到原始问题中 - 谢谢

标签: php arrays simplexml nodes


【解决方案1】:

XPath 可用于搜索包含当前类别的父 id 的类别。

foreach($cat_xml as $cat) {
    $cat_id = intval($cat->id);
    // Find categories that call this one their parent
    $child_cats = $cat_xml->xpath("/categories/category[parentID/text()={$cat_id}]");
    if (!empty($child_cats)){
        //display if cat is top level or has been selected 
        if ($cat->parentID == $cat_parent_id){
            // ....
        }
    } else {
        echo '<p>There are no sub categories.</p>';
    }
}

【讨论】:

    猜你喜欢
    • 2015-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    • 2015-10-23
    • 2018-11-13
    • 2014-02-18
    相关资源
    最近更新 更多