使用PHP中的SimpleXML使用命名空间创建RSS元素

时间:2016-04-06 06:20:10

标签: php xml rss

我尝试创建一个RSS Feed,其中一个元素是

<content:encoded></content:encoded>

但是,当我使用这段代码时:

$item->addChild('content:encoded',htmlspecialchars($itemdata->description));

我得到了这个结果:

<encoded> .................. </encoded>

我没有获得内容命名空间,我怎么能够?

1 个答案:

答案 0 :(得分:2)

正如您在documentation中所看到的,您需要提供名称空间URI作为addChild()的第三个参数,以便在命名空间中正确创建元素:

$item->addChild(
        'content:encoded',
        htmlspecialchars($itemdata->description),
        'namespace-URI-for-content-prefix-here'
    );

快速演示:

$raw = '<root xmlns:content="mynamespace"></root>';
$item = new SimpleXMLElement($raw);
$item->addChild(
          'content:encoded',
          'foo bar baz',
          'mynamespace'
      );
echo $item->asXML();

<强> eval.in demo

输出

<?xml version="1.0"?>
<root xmlns:content="mynamespace"><content:encoded>foo bar baz</content:encoded></root>