名前空間プレフィックスがあるXMLファイルをPHPにsimplexml_load_fileで変換した場合の属性にアクセスするための方法を、livedoor天気APIで地域設定に使う 全国の地点定義表(RSS)のXMLファイルを例にメモ書きします。
【XMLファイルの例(全国の地域定義表より)】
<channel>
<ldWeather:provider name="日本気象協会" link="http://tenki.jp/" />
<ldWeather:source title="全国" link="http://weather.livedoor.com/forecast/rss/index.xml">
<pref title="道北">
<warn title="警報・注意報" source="http://weather.livedoor.com/forecast/rss/warn/01a.xml" />
<city title="稚内" id="011000" source="http://weather.livedoor.com/forecast/rss/area/011000.xml" />
<city title="旭川" id="012010" source="http://weather.livedoor.com/forecast/rss/area/012010.xml" />
<city title="留萌" id="012020" source="http://weather.livedoor.com/forecast/rss/area/012020.xml" />
</pref>
<pref title="道東">
<warn title="警報・注意報" source="http://weather.livedoor.com/forecast/rss/warn/01c.xml" />
<city title="網走" id="013010" source="http://weather.livedoor.com/forecast/rss/area/013010.xml" />
<city title="北見" id="013020" source="http://weather.livedoor.com/forecast/rss/area/013020.xml" />
</pref>
</ldWeather:source>
</channel>
「ldweather:provider」や「ldWeather:source」などコロンがあるXMLデータをsimplexml_load_fileで取得して表示しようとしても、そのままですとechoなどを使用してもプレフィックス部分のXMLデータは表示されません。
プレフィックス部分のデータにアクセスするには、例えば、「ldWeather:source」にある属性「title」の値を取得する場合は、channelの子要素を取得するのにchildren()を使い、そのあとにプレフィックス名を設定、次に属性を取得するattributes()を設定して最後に属性名を設定します。
$xml = simplexml_load_file($base_url);
echo $xml->channel->children('ldWeather', true)->source->attributes()->title;
また、上記のXMLデータから地域idと地域名を取得(表示)するには、下のコードでできます。simplexml_load_fileでXMLファイルを取得したあと、2行目のコードで「ldWeather:source」の子要素を取得、foreachでxmlデータの各prefにある子要素を取得していくコードになります。
地域名とidを取得(表示)するので、prefの子要素にあるcity要素だけ取り出すので、getName()で要素を取得して比較しています。
$xml = simplexml_load_file($base_url);
$xml = $xml->channel->children('ldWeather', true)->source->children();
foreach( $xml as $pref ) {
foreach( $pref->children() as $pchild ) {
if( $pchild->getName() == 'city' ) {
echo $pchild->attributes()->title;
echo $pchild->attributes()->id . '<br />';
}
}
}
スポンサーリンク

コメント