duanji7881 2015-12-04 19:53
浏览 57
已采纳

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

I'm trying to generate a RSS feed using PHP SimpleXMLElement, the problem is that i need to prefix elements and can't find a way to do this using the SimpleXMLElement class.

I've tried using $item->addChild('prefix:element', 'value') but in the result xml it strips the prefix, any idea why this happens ?.

I wonder if there is a way to solve this using the SimpleXMLElement or any other cleaner way than just echoing the XML.

For clarification, this is my PHP code:

    $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();

And this is the example XML i'm trying to generate:

<?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>
...

Thanks in advance

  • 写回答

1条回答 默认 最新

  • doushan9415 2015-12-04 22:22
    关注

    You need to pass the namespace uri of the prefix to add child element with prefix :

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

    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();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分