普通网友 2015-10-04 10:44
浏览 64
已采纳

使用PHP解析XML文件(cs-s75:David Malan's)

I am making a PHP project for a Pizza Shop [This is project-0 in David Malan's course CS-S75 Building Dynamic Websites]. And the Code that I have to write must be eXtensible. That is, if the pizza shop's owner wants to add a new category, he should be able to do that pretty easily and my PHP code must accommodate those changes in the XML file without writing any new code.

For my code to be extensible though, I need some methods for filtering the XML data.
For instance inside the root node <menu>, I have child nodes item that have attributes like

    <item name="Pizzas">
        <category name="Onions">
        </category>
    </item>

    <item name="Salads">
        <category name = "Garden">
        </category>
    </item>

and there are ten item tags in total.

What I want to do is this: if the user wants to purchase the salads, I would want to filter the XML DOM tree the following way:

// $_POST['selected'] has a value of 'Salads' stored in it
$selected = $_POST['selected'] 
$dom = simple_xml_loadfile("menu.xml")
foreach ($dom -> xpath("menu/item[@name = $selected ]" as $item))
{
   echo $item -> category['name'].'<br />';
}

And it should print Garden and any other item that is subsequently added to the Salads category.The problem occurs with the menu/item[@name = $selected ] because this is probably not a proper method for comparing the attribute (Note that attribute comparison like this in XML requires single equal sign and not double equal).And obviously menu/item[@name = $_POST['selected']] doesn't work either. What works is @name = "Salads" and of course this kills the whole purpose of the extensiblity of XML and dynamism of PHP.
Please help!

  • 写回答

1条回答 默认 最新

  • duancuan7057 2015-10-04 11:41
    关注

    Let's get all category nodes that belong to a parent node that has a name attribute of your choosing:

    Also note that the function name is simplexml_load_file and not simple_xml_loadfile

    foreach ($dom->xpath('item[@name="' . $selected . '"]/category') as $item)
    {
       echo $item->attributes()->{'name'}. PHP_EOL;
    }
    

    Also note the usage of single vs. double quotes to enclose the attribute value.

    For reference, this is the xml structure I used for testing:

    <menu>
    <item name="Pizzas">
        <category name="Onions"></category>
    </item>
    <item name="Salads">
        <category name = "Garden"></category>
        <category name = "Cesar"></category>
        <category name = "Onion and Tomato"></category>
    </item>
    </menu>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用
  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用