Generate XML with namespace URI in PHP

后端 未结 2 891
长情又很酷
长情又很酷 2021-01-15 13:30

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



        
相关标签:
2条回答
  • 2021-01-15 13:41

    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: http://us2.php.net/manual/en/book.dom.php

    0 讨论(0)
  • 2021-01-15 13:56

    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();
    
    0 讨论(0)
提交回复
热议问题