2014-04-15 89 views
0

因为我将解析一个非常大的XML文件,所以我试图使用XMLReader来检索XML数据,并使用simpleXML来显示。我从来没有使用XMLreader,所以我只是试图获得使用XMLReader的基本感受。我想在XML文件中显示所有名称和价格值,并且我无法获取此代码以显示任何内容。我错过了什么吗?PHP - 非常基本的XMLReader

这里是的XMLReader/SimpleXML的代码:

$z = new XMLReader; 
$z->open('products.xml'); 
$doc = new DOMDocument; 

while ($z->read() && $z->name === 'product') { 
$node = simplexml_import_dom($doc->importNode($z->expand(), true)); 

var_dump($node->name); 
$z->next('product'); 
} 

下面是XML文件,命名为products.xml

<products> 

<product category="Desktop"> 
<name> Desktop 1 (d)</name> 
<price>499.99</price> 
</product> 

<product category="Tablet"> 
<name>Tablet 1 (t)</name> 
<price>1099.99</price> 
</product> 

</products> 

回答

1

你的循环状态被打破了。如果你得到一个元素并且元素名称是“product”,则循环。文档元素是“products”,所以循环条件永远不会是TRUE

您必须注意,read()next()正在移动内部游标。如果它位于<product>节点上,则read()将把它移动到该节点的第一个子节点。

$reader = new XMLReader; 
$reader->open($file); 
$dom = new DOMDocument; 
$xpath = new DOMXpath($dom); 

// look for the first product element 
while ($reader->read() && $reader->localName !== 'product') { 
    continue; 
} 

// while you have an product element 
while ($reader->localName === 'product') { 
    $node = $reader->expand($dom); 
    var_dump(
    $xpath->evaluate('string(@category)', $node), 
    $xpath->evaluate('string(name)', $node), 
    $xpath->evaluate('number(price)', $node) 
); 
    // move to the next product sibling 
    $reader->next('product'); 
} 

输出:

string(7) "Desktop" 
string(14) " Desktop 1 (d)" 
float(499.99) 
string(6) "Tablet" 
string(12) "Tablet 1 (t)" 
float(1099.99) 
+0

谢谢!您引导我朝着正确的方向发展 - 足以让我能够在XMLReader解析XML后,将simpleXML合并到显示结果中。 –

+0

我更喜欢使用DOM + XPath。 SimpleXML很有用。 – ThW

+0

在这方面的工作,我相信你是正确的simpleXML是太多的工作。我对编程相对比较陌生,所以非常感谢您的帮助! –