Simplexml给了我错误的结果

时间:2010-01-21 08:03:27

标签: php xml dom simplexml

我在下面有一个简单的xml:

<?xml version="1.0" encoding="utf-8"?>
<catalogue>
  <category name="textbook" id="100" parent="books">
    <product id="20000">
      <author>Gambardella, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
    </product>
    <product id="20001">
      <author>Gambardellas, Matthew</author>
      <title>XML Developer's Guide</title>
      <genre>Computer</genre>
      <price>44.95</price>
      <publish_date>2000-10-01</publish_date>
      <description>An in-depth look at creating applications
      with XML.</description>
    </product>
  </category>
  <category name="fiction" id="101" parent="books">
    <product id="2001">
      <author>Ralls, Kim</author>
      <title>Midnight Rain</title>
      <genre>Fantasy</genre>
      <type>Fiction</type>
      <price>5.95</price>
      <publish_date>2000-12-16</publish_date>
      <description>A former architect battles corporate zombies, an evil sorceress,                  and her own childhood to become queen
      of the world.</description>
    </product>
  </category>
</catalogue>

我使用php simplexml库解析它如下:(注意有两个类别节点。第一个类别包含两个'product'子节点。我的目标是获取一个包含第一个'category'的两个子节点的数组

$xml = simplexml_load_file($xml_file) or die ("unable to load XML File!".$xml_file);

//for each product, print out info
$cat = array();
foreach($xml->category as $category)
{
    if($category['id'] == 100)
    {
        $cat = $category;       
        break;
    }
}
$prod_arr = $category->product;

这是问题所在。我期待一个有两个产品儿童的阵列,但它只返回一个产品。我做错了什么或者这是一个php bug?请帮忙!

3 个答案:

答案 0 :(得分:2)

您可以使用SimpleXMLElement::xpath()获取属于特定类别元素的子元素的所有产品元素。 E.g。

 // $catalogue is your $xml
 $products = $catalogue->xpath('category[@id="100"]/product');
 foreach($products as $p) {
   echo $p['id'], ' ', $p->title, "\n";
 }

打印

20000 XML Developer's Guide
20001 XML Developer's Guide

答案 1 :(得分:1)

首先,您的XML文件定义不明确。你应该用<categories>标签开始和结束它。

用以下内容替换最后一项作业:

$prod_array = array();
foreach ($cat->product as $p) {
    $prod_array[] = $p;
}

答案 2 :(得分:0)

$cat = array();
foreach ($xml->category as $category)
{
    $attributes = $category->attributes();
    if(isset($attributes['id']) && $attributes['id'] == 100)
    {
        $cat = $category;
        break;
    }
}