普通网友 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>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 用HslCommunication 连接欧姆龙 plc有时会连接失败。报异常为“未知错误”
  • ¥15 网络设备配置与管理这个该怎么弄
  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?