views:

4218

answers:

10

Is there an easy way to marshal a PHP associative array to and from XML? For example, if I have the following array:

$items = array("1", "2",
    array(
        "item3.1" => "3.1",
        "item3.2" => "3.2"
        "isawesome" => true
    )
);

How would I turn it into something similar to the following XML in as few lines as possible, then back again:

<items>
    <item>1</item>
    <item>2</item>
    <item>
        <item3_1>3.1</item3_1>
        <item3_2>3.2</item3_2>
        <isawesome>true</isawesome>
    </item>
</items>

I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's XMLReader and XMLWriter, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:

$xml = SomeXMLWriter::writeArrayToXml($items);
$array = SomeXMLWriter::writeXmlToArray($xml);

Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?

@cruizer, I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.

@Oddmund & Jared Can you please provide some examples of using SimpleXML to do what I am trying to do?

A: 

Have you seen the PEAR package XML_Serializer?

http://pear.php.net/package/XML_Serializer

cruizer
+10  A: 

SimpleXML works great for your use.

Oddmund
+2  A: 

Try Zend_Config and Zend Framework in general.

I imagine it would be a 2 step process: array to Zend_Config, Zend_Config to XML.

Edward Hyde
+2  A: 

Sounds like a job for SimpleXML.

I would suggest a slightly different XML structure..

And wonder why you need to convert from an array -> XML and back.. If you can modify the array structure as you said why not just generate XML instead? If some piece of code already exists that takes that array configuration, just modify it to accept the XML instead. Then you have 1 data format/ input type, and don't need to convert at all..

<items>
  <item id="1"/>
  <item id="2"/>
  <item id="3">
  <subitems>     
    <item id="3.1"/>
    <item id="3.2" isawesome="true"/>
  </subitems>
  </item>
</items>
DreamWerx
+1  A: 

I agree this is one area that PHP's documentation has dropped the ball, but for me I've always used the SimpleXML mixed with something like the xml2Array functions. The Xml you get from simpleXML isn't that hard to navigate with the help of a dumping function like print_r.

SeanDowney
+1  A: 

Seconding SimpleXML - I have used it extensively to do exactly what you're asking.

Jared
+2  A: 

I've had some of these same issues, and so I created two classes:

bXml

A class that extends SimpleXml and corrects some of the problems it has. Like not being able to add CData nodes or Comment nodes. I also added some additional features, like using the php streams functionality to add child nodes $oXml->AddChild("file:///user/data.xml") or add XML string child nodes like $oXml->AddChild("<more><xml>yes</xml></more>"); but basically I just wanted to fix the simpleXML problems.

bArray

I extended the ArrayObject class so that all array functionality could be object oriented and consistent, so you don't need to remember that array_walk operates on the array by reference, while array_filter operates on the array by value. So you can do things like $oArray->flip()->Reverse()->Walk(/*callback*/); then still access the value the same way you normally would like $oArray[key].

Both of the methods output themselves as Arrays and Xml so you can jump seamlessly between them. So you can $oXml->AsArray(); or $oArray->AsXml(); I found that it was easier to do this than to constantly pass things back and forth between array2xml or xml2array methods.

http://code.google.com/p/blibrary/source

Both classes are can be overridden to make a custom class of your choosing and can be used independently of one another.

Extending SimpleXML to do that is a pretty neat idea!
thomasrutter
A: 

Following class uses simplexml to achieve the same, you just need to loop through the array and call addchild of ximplexml.

http://snipplr.com/view.php?codeview&amp;id=3491

+1  A: 

For those of you not using the PEAR packages, but you've got PHP5 installed. This worked for me:

    /**
 * Build A XML Data Set
 *
 * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)
 * @param string $startElement Root Opening Tag, default fx_request
 * @param string $xml_version XML Version, default 1.0
 * @param string $xml_encoding XML Encoding, default UTF-8
 * @return string XML String containig values
 * @return mixed Boolean false on failure, string XML result on success
 */
public function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){
  if(!is_array($data)){
     $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__." in Class: ".__CLASS__." Method: ".__METHOD__;
     trigger_error($err);
     if($this->_debug) echo $err;
     return false; //return false error occurred
  }
  $xml = new XmlWriter();
  $xml->openMemory();
  $xml->startDocument($xml_version, $xml_encoding);
  $xml->startElement($startElement);

  /**
   * Write XML as per Associative Array
   * @param object $xml XMLWriter Object
   * @param array $data Associative Data Array
   */
  function write(XMLWriter $xml, $data){
      foreach($data as $key => $value){
          if(is_array($value)){
              $xml->startElement($key);
              write($xml, $value);
              $xml->endElement();
              continue;
          }
          $xml->writeElement($key, $value);
      }
  }
  write($xml, $data);

  $xml->endElement();//write end element
  //Return the XML results
  return $xml->outputMemory(true); 
}
Conrad
if you have non-associative arrays (or rather, array keys with numbers in them) in your data, adding a 'if (is_numeric($key)) $key = "item";' at the start of the foreach block (before is_array) does the trick.
disq
A: 

Can you please tell me an alternative...SimpleXML and using json_encode and json_decode results in me losing attributes on some of my nodes!

See http://bonsai.php.net/bug.php?id=46309&amp;edit=1

SimpleXML was easy to use...json_encode and json_decode were easy to use... but ended up with me losing attribute information!!! What is an easy, but lossless, alternative???

Argh