2

Ho to make this "simple" xml with php using DOM? Full code will be welcomed.

<rss version="2.0"
  xmlns:wp="http://url.com"
  xmlns:dc="http://url2.com"
>
 <channel>
  <items>
   <sometags></sometags>
   <wp:status></wp:status>
  </items>
 </channel>
</rss>

i'm so lost. Code will help me more than any explanation.

2 Answers 2

7

Here is the code:

<?php
$dom = new DOMDocument('1.0', 'utf-8');

$rss = $dom->createElement('rss');
$dom->appendChild($rss);

$version = $dom->createAttribute('version');
$rss->appendChild($version);

$value = $dom->createTextNode('2.0');
$version->appendChild($value);

$xmlns_wp = $dom->createAttribute('xmlns:wp');
$rss->appendChild($xmlns_wp);

$value = $dom->createTextNode('http://url.com');
$xmlns_wp->appendChild($value);

$xmlns_dc = $dom->createAttribute('xmlns:dc');
$rss->appendChild($xmlns_dc);

$value = $dom->createTextNode('http://url2.com');
$xmlns_dc->appendChild($value);

$channel = $dom->createElement('channel');
$rss->appendChild($channel);

$items = $dom->createElement('items');
$channel->appendChild($items);

$sometags = $dom->createElement('sometags', '');
$items->appendChild($sometags);

$wp_status = $dom->createElement('wp:status', '');
$items->appendChild($wp_status);

echo $dom->saveXML();
?>

It outputs:

<?xml version="1.0" encoding="utf-8"?>
<rss 
  version="2.0" 
  xmlns:wp="http://url.com" 
  xmlns:dc="http://url2.com"
>
  <channel>
    <items>
      <sometags></sometags>
      <wp:status></wp:status>
    </items>
  </channel>
</rss>

Fore more help: https://www.php.net/manual/en/book.dom.php

Sign up to request clarification or add additional context in comments.

Comments

3

If you want "simple" then use SimpleXML, not DOM. Note that SimpleXML won't indent the XML.

$rss = simplexml_load_string('<rss version="2.0" xmlns:wp="http://url.com" xmlns:dc="http://url2.com" />');

$channel  = $rss->addChild('channel');
$items    = $channel->addChild('items');
$sometags = $items->addChild('sometags');
$status   = $items->addChild('status', null, 'http://url.com');

echo $rss->asXML();

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.