SimpleXML的是给我错误的结果

问题描述:

下面我有一个简单的XML:SimpleXML的是给我错误的结果

<?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的库来解析它,如下所示:(注意有两个类别节点第一类包含两个“。产品”的孩子。我的目标是获得一个包含第一的那两个孩子的数组‘类别’

$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的错误?请帮助!

您可以使用SimpleXMLElement::xpath()来获取在一个特定的类别元素的所有子产品元素。例如。

// $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 

首先,您的XML文件没有很好的定义。你可能应该用 <categories>标签来开始和结束它。

使用以下内容替换最后一个任务:

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

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

永远不要忘记埋怨代码之前验证XML文件。这很简单,只需用firefox打开你的文件(或者在Linux下尝试xmllint命令),它会告诉你错误出现在哪里。 – OcuS 2010-01-21 08:22:58

+0

我根据你的编辑修复了我的代码:) – OcuS 2010-01-21 08:28:12