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 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)