Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to write XML using PHP - how?

Tags:

php

xml

I've got this basic code.

<chart lowerLimit='0' upperLimit='100' caption='Revenue' subcaption='US $ (1,000s)' numberPrefix='$' numberSuffix='K' showValue='1' >
   <colorRange>
      <color minValue='0' maxValue='50' color='A6A6A6'/>
      <color minValue='50' maxValue='75' color='CCCCCC'/> 
      <color minValue='75' maxValue='100' color='E1E1E1'/> 
   </colorRange> 
   <value>78.9</value>
   <target>80</target>
</chart>

it's used from fusionwidgets and there's no documentation on how to write this in PHP.

can anybody advise?


1 Answers

My favorite way to write XML files is XMLWriter - http://php.net/xmlwriter . It's very powerfull and simple to use.

<?php
           $writer = new XMLWriter();  
           $writer->openURI('php://output');   
           $writer->startDocument('1.0','UTF-8');   
           $writer->setIndent(4);   
           $writer->startElement('items');  
           $writer->startElement("main");  
           $writer->writeElement('user_id', 3);  
           $writer->writeElement('msg_count', 11);  
           $writer->endElement();   
           $writer->startElement("msg");  
           $writer->writeAttribute('category', 'test');  
           $writer->endElement();     
           $writer->endElement();   
           $writer->endDocument();   
           $writer->flush(); 
    ?>

And that piece of code will produce the following XML:

<?xml version="1.0" encoding="UTF-8"?>
<items>
 <main>
  <user_id>3</user_id>
  <msg_count>11</msg_count>
 </main>
 <msg category="test"/>
</items>
like image 147
Māris Kiseļovs Avatar answered Sep 15 '25 06:09

Māris Kiseļovs