使用XMLReader和SimpleXML从具有特定参数名称

时间:2016-01-22 17:37:20

标签: php xml simplexml xmlreader

我正在尝试学习如何使用XMLReader和SimpleXML来读取大型xml文件,并能够从中检索各种数据。我的问题是按元素从元素中检索数据。

例如,如果我有XML:

<Product>
    <CustomParameter Name="companyName">Company A</CustomParameter>
    <CustomParameter Name="productName">Shiny Black Shoes</CustomParameter>
    <CustomParameter Name="productUrl">http://www.example.com</CustomParameter>
    <CustomParameter Name="companyUrl">http://www.example.com</CustomParameter>
</Product>
<Product>
    <CustomParameter Name="companyName">Company B</CustomParameter>
    <CustomParameter Name="productName">Boots</CustomParameter>
    <CustomParameter Name="productUrl">http://www.example.com</CustomParameter>
    <CustomParameter Name="companyUrl">http://www.example.com</CustomParameter>
</Product>

我想只检索CustomParameter的数据,名称为&#34; productName&#34;属性。

我正在使用此代码,但它只显示第一个找到的CustomParameter。

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

$doc = new DOMDocument;

$product_name = array();

// move to the first <product /> node
while ($z->read() && $z->name !== 'Product');

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

    $product_name[] = $node->CustomParameter;

    $z->next('Product');
 }

 $product_name = array_unique($product_name);

foreach($product_name as $value)
     echo $value."\n";

有人可以解释如何阅读我想要的具体内容吗?

由于

1 个答案:

答案 0 :(得分:1)

在产品while循环中,您可以迭代每个 CustomParameter 标记,测试属性值,如下所示:

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

    foreach($node->children() as $child) {
        if ($child["Name"] == "productName") {
            $product_name[] = (string) $child;
        }
    }

    $z->next('Product');
}

但是,如果您使用xpath搜索,则可以缩短代码,如下所示:

$xmlDoc = simplexml_load_file('products.xml');

// locate the nodes of interest through an XPath descriptor:
$result = $xmlDoc->xpath('/Products/Product/CustomParameter[@Name="productName"]');

while(list( , $node) = each($result)) {
    $product_name[] = (string) $node;
}

在上面的代码中,您应该将XPath值替换为元素的真实路径。由于您没有提供整个XML文档,我只是假设产品标记出现在 Products (复数)包装器标记中,这是根元素。当然,你的实际情况可能会有所不同,但应该很容易适应。

相关问题