iTunes用のRSSをSimpleXMLで出力したときに、なぜか <itunes:iamge>
が <image>
にならないという問題が、suin/php-rss-writerのissueとして相談?があったので調べてみた。どうやら、PHPのSimpleXMLのaddChild
メソッドはネームスペースを指定しないとコロン以前(itunes
の部分)を削り捨ててしまう挙動らしい。
正しく itunes
の部分を出力するには、addChild
メソッドの第三引数でネームスペースを指定するといい。
<itunes:iamge>
を追加したつもりが<image>
になってしまうするコード
<?php
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rss />', LIBXML_NOERROR|LIBXML_ERR_NONE|LIBXML_ERR_FATAL);
$itunesImage = $xml->addChild('itunes:image', null);
$itunesImage->addAttribute('url', 'http://example.com/example.png');
$result = $xml->asXML();
echo $result;
実行結果
<?xml version="1.0" encoding="UTF-8"?>
<rss><image url="http://example.com/example.png"/></rss>
<itunes:iamge>
がちゃんと出力されるコード
<?php
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8" ?><rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd">', LIBXML_NOERROR|LIBXML_ERR_NONE|LIBXML_ERR_FATAL);
$itunesImage = $xml->addChild('itunes:image', null, 'http://www.itunes.com/dtds/podcast-1.0.dtd');
$itunesImage->addAttribute('url', 'http://example.com/example.png');
$result = $xml->asXML();
echo $result;
実行結果
<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"><itunes:image url="http://example.com/example.png"/></rss>
ポイント
- XMLのルートノードに
xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"
属性を定義する -
addChild
メソッドの第三引数にネームスペースのURLを渡す。