属性(attribute)の取得[XML DOM関数]

ここでは、XMLから属性(attribute)を取得する方法を見てみます。

サンプルとしてlivedoorのお天気情報サービス(Livedoor Weather Web Service / LWWS)を
使用しています。

http://weather.livedoor.com/forecast/webservice/rest/v1?city=84&day=today

属性(attribute)の名前から値を取得

XML DOM関数で、属性(attribute)の名前から属性オブジェクトを取得するにはget_attribute()
を使用します。この関数は、XML_ELEMENT_NODEタイプで使用することができます。

livedoorのお天気情報サービス(Livedoor Weather Web Service / LWWS)を例に取得して見ます。
get_elements_by_tagname()関数に'location'というタグ名を指定することで要素を取得します。
locationタグの属性areaを取得します。

<?php

$request = "http://weather.livedoor.com/forecast/webservice/rest/v1?city=84&day=today";

$weatherxml = file_get_contents($request);

$dom = @domxml_open_mem($weatherxml,
        (DOMXML_LOAD_PARSING | 
        DOMXML_LOAD_COMPLETE_ATTRS | 
        DOMXML_LOAD_SUBSTITUTE_ENTITIES | 
        DOMXML_LOAD_DONT_KEEP_BLANKS ));

//imageタグの取得
$element = $dom->get_elements_by_tagname('location');
$area = $element[0]->get_attribute('area');

echo $area;

?>

取得結果は、次のようになります。

近畿

要素の属性(attribute)を全て取得する

要素オブジェクトから属性(attribute)を全て取得するには、attributes()を使用します。
先ほどのlocation要素から属性(attribute)を全て取得します。

<?php

$request = "http://weather.livedoor.com/forecast/webservice/rest/v1?city=84&day=today";

$weatherxml = file_get_contents($request);

$dom = @domxml_open_mem($weatherxml,
        (DOMXML_LOAD_PARSING | 
        DOMXML_LOAD_COMPLETE_ATTRS | 
        DOMXML_LOAD_SUBSTITUTE_ENTITIES | 
        DOMXML_LOAD_DONT_KEEP_BLANKS ));

//imageタグの取得
$element = $dom->get_elements_by_tagname('location');
$attr = $element[0]->attributes();

var_dump($attr);

?>

結果は、次のようになります。各属性は、DomAttributeオブジェクトになります。

array(3) {
  [0]=>
  object(domattribute)(5) {
    ["type"]=>int(2)
    ["name"]=>string(4) "area"
    ["value"]=>string(6) "近畿"
    [0]=>int(38)
    [1]=>int(157640960)
  }
  [1]=>
  object(domattribute)(5) {
    ["type"]=>int(2)
    ["name"]=>string(4) "pref"
    ["value"]=>string(9) "奈良県"
    [0]=>int(39)
    [1]=>int(157641112)
  }
  [2]=>
  object(domattribute)(5) {
    ["type"]=>int(2)
    ["name"]=>string(4) "city"
    ["value"]=>string(6) "奈良"
    [0]=>int(40)
    [1]=>int(157641264)
  }
}