【问题标题】:how confirm / check weather a tag exists or not in XML如何在 XML 中确认/检查标签是否存在
【发布时间】:2014-03-19 10:04:24
【问题描述】:

我正在尝试使用 DOM 解析器读取 XML。我的XML 是动态的,所以我不能说所有值/标签都会出现在XML 中。在这种情况下,我需要在阅读之前检查标签是否存在。

我也试过这样

if($val->getElementsByTagName("cityName") != null) {

}

if(!empty($val->getElementsByTagName("cityName"))) {

}

getting error : Fatal error: Call to a member function getElementsByTagName() on a non-object in F:\xampp\htdocs\test\static-data.php on line 160

找到标签存在的任何解决方案。就像有属性一样,我们检查天气属性是否存在。

【问题讨论】:

    标签: php xml dom xml-parsing


    【解决方案1】:

    如果你使用 Xpath 来获取节点,你可以避免验证。

    加载一些 XML 并为其创建一个 DOMXpath 实例。

    $xml = <<<XML
    <phoneNumbers>
      <phoneNumber type="home">212 555-1234</phoneNumber>
      <phoneNumber type="fax">646 555-4567</phoneNumber>
    </phoneNumbers>
    XML;
    
    $dom = new DOMDocument();
    $dom->loadXml($xml);
    $xpath = new DOMXpath($dom);
    

    获取“家”电话号码:

    var_dump(
      $xpath->evaluate('string(/phoneNumbers/phoneNumber[@type="home"])')
    );
    

    输出:

    string(12) "212 555-1234"
    

    不存在“手机”号码,因此结果为空字符串

    var_dump(
      $xpath->evaluate('string(/phoneNumbers/phoneNumber[@type="mobile"])')
    );
    

    输出:

    string(0) ""
    

    你可以数数:

    var_dump(
      [
        'all' => $xpath->evaluate('count(/phoneNumbers/phoneNumber)'),
        'home' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="home"])'),
        'fax' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="fax"])'),
        'mobile' => $xpath->evaluate('count(/phoneNumbers/phoneNumber[@type="mobile"])')
      ]
    );
    

    输出:

    array(4) {
      ["all"]=>
      float(2)
      ["home"]=>
      float(1)
      ["fax"]=>
      float(1)
      ["mobile"]=>
      float(0)
    }
    

    或者迭代数字

    foreach ($xpath->evaluate('/phoneNumbers/phoneNumber') as $phoneNumber) {
      var_dump(
        $phoneNumber->getAttribute('type'),
        $phoneNumber->nodeValue
      );
    }
    

    输出:

    string(4) "home"
    string(12) "212 555-1234"
    string(3) "fax"
    string(12) "646 555-4567"
    

    完整示例:https://eval.in/123212

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      • 2018-06-08
      • 1970-01-01
      • 2018-03-04
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      相关资源
      最近更新 更多