【问题标题】:Add rss xmlns namespace definition to a php simplexml document?将 rss xmlns 命名空间定义添加到 php simplexml 文档?
【发布时间】:2010-04-15 09:58:39
【问题描述】:

我正在尝试使用 php5 的 simplexml 创建一个 iTunes 有效的播客提要:

<?php   
$xml_string = <<<XML
<?xml version="1.0" encoding="UTF-8"?>


<channel>
</channel>
XML;

$xml_generator = new SimpleXMLElement($xml_string);
           $tnsoundfile = $xml_generator->addChild('title', 'Main Title');
           $tnsoundfile->addChild('itunes:author', "Author", ' ');
           $tnsoundfile->addChild('category', 'Audio Podcasts'); 
           $tnsoundfile = $xml_generator->addChild('item');
           $tnsoundfile->addChild('title', 'The track title');        
           $enclosure = $tnsoundfile->addChild('enclosure');
           $enclosure->addAttribute('url', 'http://test.com');
           $enclosure->addAttribute('length', 'filelength');
           $enclosure->addAttribute('type', 'audio/mpeg');       
           $tnsoundfile->addChild('itunes:author', "Author", ' '); 


header("Content-Type: text/xml");
echo $xml_generator->asXML();

?>

它不验证,因为我必须把这条线:

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

根据http://www.apple.com/itunes/podcasts/specs.html

所以输出应该是:

<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">
<channel>

等等。我已经一遍又一遍的手册和论坛,只是无法正确。如果我把,靠近页脚:

header("Content-Type: text/xml");
echo '<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">';
echo $xml_generator->asXML();
?>

然后它在 Firefox 中看起来很正确,它不再抱怨未定义的命名空间,但 feedvalidator 抱怨

第 1 行,第 77 列:XML 解析错误: :1:77: xml 声明不在 外部实体的开始 [帮助]

因为文档现在开始:

<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0"><?xml version="1.0" encoding="UTF-8"?>

而不是

<?xml version="1.0" encoding="UTF-8"?><rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd" version="2.0">

【问题讨论】:

    标签: php xml simplexml itunes


    【解决方案1】:

    问题中显示的代码不起作用,因为它没有使用正确的命名空间。具体来说,这些行:

    $tnsoundfile->addChild('itunes:author', "Author", ' ');
    

    他们将在“”(一个空格)命名空间中创建一个&lt;author/&gt; 节点,这显然是不正确的。它应该是:

    $tnsoundfile->addChild('itunes:author', "Author", 'http://www.itunes.com/dtds/podcast-1.0.dtd');
    

    这是使用命名空间的正确方法。

    【讨论】:

      【解决方案2】:

      这在 SimpleXML 中是非常可能的。只需在构造函数字符串中声明命名空间,而不是作为属性。

      $rss_xml = new SimpleXMLElement(
         '<rss xmlns:itunes="http://www.itunes.com/dtds/podcast-1.0.dtd"/>');
      $rss_xml->addAttribute('version', '2.0');
      

      【讨论】:

        猜你喜欢
        • 2011-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多