解析XML子节点


Parse through XML childs

我有以下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>

我如何确保产品信息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是否存在?

感谢您的努力!

您正在寻找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中最简单的…