小编Nod*_*era的帖子

如何在PHP中使用SimpleXMLElement生成名称空间前缀的xml元素

我正在尝试使用PHP生成RSS提要SimpleXMLElement,问题是我需要为元素添加前缀,并且无法使用SimpleXMLElement类找到这样做的方法.

我尝试过使用$item->addChild('prefix:element', 'value')但在结果xml中它会删除前缀,任何想法为什么会发生这种情况?.

我想知道是否有办法使用SimpleXMLElement或者任何其他简洁的方式来解决这个问题,而不仅仅是回应 XML.

为了澄清,这是我的PHP代码:

    $xml = new SimpleXMLElement('<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0"/>');
    $channel = $xml->addChild('channel');
    $channel->addChild('title', 'Text');
    $channel->addChild('link', 'http://example.com');
    $channel->addChild('description', 'An example item from the feed.');

    foreach($this->products as $product) {
        $item = $channel->addChild('item');

        foreach($product as $key => $value)
            $item->addChild($key, $value);
    }

    return $xml->asXML();
Run Code Online (Sandbox Code Playgroud)

这是我正在尝试生成的示例XML:

<?xml version="1.0"?>
<rss xmlns:g="http://base.google.com/ns/1.0" version="2.0">
<channel>
    <title>Test Store</title>
    <link>http://www.example.com</link>
    <description>An example item from the feed</description>

    <item>
        <g:id>DB_1</g:id>
        <g:title>Dog Bowl In Blue</g:title>
        <g:description>Solid …
Run Code Online (Sandbox Code Playgroud)

php xml

6
推荐指数
1
解决办法
104
查看次数

标签 统计

php ×1

xml ×1