【问题标题】:simplexml: access attribute country's value [duplicate]simplexml:访问属性国家/地区的值[重复]
【发布时间】:2023-03-25 19:36:02
【问题描述】:

我需要从以下访问属性国家/地区的值(不使用 xpath): http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml

这是我到目前为止所做的

$xml = simplexml_load_file("http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml");
$country = $xml->objects->object->attributes->attribute ... ???

【问题讨论】:

    标签: php simplexml


    【解决方案1】:
    $xml = simplexml_load_file('http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml');
    foreach ($xml->objects->object->attributes->attribute as $attr) {
       if ($attr->attributes()->name == 'country') {
          echo $attr->attributes()->value;
       }
    }
    

    【讨论】:

    • 如果没有类型转换,这将无法工作。
    • 我让它在没有类型转换的情况下工作。请参阅 PHP 的文档示例 php.net/manual/en/simplexmlelement.attributes.php
    • 是的,这只是 xdebug 向我展示了一个空的 SimpleXMLElement 对象。
    【解决方案2】:

    这行得通;

    $s = simplexml_load_file("http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml");
    foreach ($s->objects->object->attributes->attribute as $attr) {
        $attrs = $attr->attributes();
        if ((string) $attrs->name == "country") {
            $country = (string) $attrs->value;
            break;
        }
    }
    print $country; // IT
    

    但是也有一个选项,如果它适合你的话;

    $s = file_get_contents("http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml");
    preg_match_all('~<attribute\s+name="country"\s+value="(.*?)".*?/>~i', $s, $m);
    print_r($m);
    

    退出;

    大批 ( [0] => 数组 ( [0] => ) [1] => 数组 ( [0] => IT ) )

    【讨论】:

      【解决方案3】:

      我刚刚找到了两种方法,使用 [ ] 和使用 attributes()。

      foreach(simplexml_load_file("http://apps.db.ripe.net/whois/lookup/ripe/inetnum/79.6.54.99.xml")->objects->object->attributes->attribute as $a){
      if($a['name'] == 'country')
      if(in_array($a['value'],array('IT'))) exit;
      else break;
      }
      

      我将把这个问题留到明天,以防万一其他人有事。

      【讨论】:

        猜你喜欢
        • 2018-07-06
        • 1970-01-01
        • 1970-01-01
        • 2013-12-23
        • 2019-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多