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

Nod*_*era 6 php 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 plastic Dog Bowl in marine blue color</g:description>
        ...
    </item>
...
Run Code Online (Sandbox Code Playgroud)

提前致谢

har*_*r07 2

您需要传递前缀的命名空间 uri 来添加带有 prefix 的子元素:

$item->addChild($key, $value, 'http://base.google.com/ns/1.0');
Run Code Online (Sandbox Code Playgroud)

eval.in demo

$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.');

$item = $channel->addChild('item');
$item->addChild('g:foo', 'bar', 'http://base.google.com/ns/1.0');

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