解析XML子项

时间:2015-08-21 15:43:55

标签: php xml xml-parsing

我有以下xml:

<?xml version="1.0" standalone="yes"?>
<Products>
 <Product>
  <name>Milk</name>
  <price>1.4</price>
  <productinfos>
   <category1 value="somecategory1"/>
   <category2 value="somecategory2"/>
   <category3 value="somecategory3"/>
  </productinfos>
 </Product>
</Products>

如何确保productinfos category1,category2或category3确实存在且不是空字符串?如果我想要以下输出,循环如何:

//output
Cat1: somecategory1
Cat3: somecategory3
Cat2: somecategory2

因为有时我解析的xml看起来不同:

<?xml version="1.0" standalone="yes"?>
<Products>
 <Product>
  <name>Milk</name>
  <price>1.4</price>
  <productinfos>
   <category1 value=""/>
   <category3 value="somecategory"/>
  </productinfos>
 </Product>
</Products>

在上面的示例中,如何检查category2是否存在?

tia for your effort!

1 个答案:

答案 0 :(得分:1)

您正在寻找SimpleXMLElement::children()方法。

https://secure.php.net/manual/en/simplexmlelement.children.php

$xml = new SimpleXMLElement(<<<XML
<?xml version="1.0" standalone="yes"?>
<Products>
    <Product>
        <name>Milk</name>
        <price>1.4</price>
        <productinfos>
            <category1 value="somecategory1"/>
            <category2 value="somecategory2"/>
            <category3 value="somecategory3"/>
        </productinfos>
    </Product>
</Products>
XML
);

// $xml is a SimpleXMLElement of <Products>
foreach ($xml->children() as $product) {
    if ($product->getName() != 'Product') {
        // ignore <Products><Cow> or whatever, if you care
        continue;
    }

    // start out assuming that everything is missing
    $missing_tags = array(
        'category1' => true,
        'category2' => true,
        'category3' => true,
    );

    // iterate through child tags of <productinfos>
    foreach ($product->productinfos->children() as $productinfo) {
        // element name is accessed using the getName() method, and
        // XML attributes can be accessed like an array
        if (isset($missing_tags[$productinfo->getName()]) &&
                !empty($productinfo['value'])) {
            $missing_tags[$productinfo->getName()] = false;
            echo $productinfo->getName() . ": " . $productinfo['value'] . "\n";
        }
    }

    // array_filter with one argument filters out any values that eval to false
    if (array_filter($missing_tags)) {
        echo "Missing tags: " . implode(", ", array_keys($missing_tags)) . "\n";
    }
}

SimpleXML扩展程序的名称并不像名称所暗示的那么直观,但它与XML一样简单......