LoginSignup
7
5

More than 5 years have passed since last update.

PHP: iTunes用RSSをSimpleXMLで出力するとき<itunes:iamge>が<image>になってしまうのはXML namespaceを定義していないから

Posted at

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を渡す。
7
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
5