6

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 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.