新手here.Trouble与PHP中的xpath()函数。
XML文件(data.xml):
<?xml version="1.0" ?>
<menu>
<food type="Pizza">
<item>
<name> Tomato & Cheese </name>
<small price="5.50"/>
<large price="9.75"/>
</item>
<item>
<name> Onions </name>
<small price="6.85"/>
<large price="10.85"/>
</item>
</food>
</menu>
PHP代码:
<?php
$xml = simplexml_load_file("data.xml");
$types = $xml->xpath("/menu/food/@type");
foreach($types as $type){
echo("<h1>$type</h1>");
$menu = $xml->xpath("/menu/food[@type=$type]");
echo("<ul>");
foreach($menu as $submenu){
echo ("<li>$submenu</li>");
}
echo("</ul>");
}
?>
我有很多种食物。我想按顺序访问它们和它们的子类型。我上面的方法有问题。我似乎无法找到它。
以下是我的预期输出。我如何使用xpath()来达到它?
预期输出:
PIZZA
=&gt;番茄&amp;干酪
=&GT;葱
=&GT;
FOO
=&GT; BAR
答案 0 :(得分:3)
您只需要一个xpath查询,如下所示:
$xml = simplexml_load_file("data.xml");
// Get food items and iterate over them
$foods = $xml->xpath("/menu/food");
foreach($foods as $food){
// print type attribute
echo("<h1>{$food["type"]}</h1>");
// Iterate over food items and print their names
echo("<ul>");
foreach($food->item as $item){
echo ("<li>$item->name</li>");
}
echo("</ul>");
}
拥有这个xml:
<?xml version="1.0" ?>
<menu>
<food type="Pizza">
<item>
<name>Tomato & Cheese</name>
<small price="5.50"/>
<large price="9.75"/>
</item>
<item>
<name>Onions</name>
<small price="6.85"/>
<large price="10.85"/>
</item>
</food>
<food type="Pasta">
<item>
<name>Bolognese</name>
<small price="5.50"/>
<large price="9.75"/>
</item>
<item>
<name>Carbonara</name>
<small price="6.85"/>
<large price="10.85"/>
</item>
</food>
</menu>
......上面的代码将产生:
<h1>Pizza</h1>
<ul>
<li>Tomato & Cheese</li>
<li>Onions</li>
</ul>
<h1>Pasta</h1>
<ul>
<li>Bolognese</li>
<li>Carbonara</li>
</ul>
答案 1 :(得分:2)
尝试更改
$menu = $xml->xpath("/menu/food[@type=$type]");
echo("<ul>");
foreach($menu as $submenu){
echo ("<li>$submenu</li>");
}
到
$menu = $xml->xpath("/menu/food[@type='$type']/item/name");
echo("<ul>");
foreach($menu as $submenu){
echo ("<li>$submenu</li>");
}