Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you merge two XML documents in PHP using SimpleXML?

Tags:

php

xml

simplexml

I have a database row that looks like this.

ID (int):       123
Name (string):  SomeName
Data (string):  <data><foo>one</foo></bar>two</bar></data>

I need to format this data as XML in the following way.

<row>
  <id>123</id>
  <name>SomeName</name>
  <data>
    <foo>one</foo>
    <bar>two</bar>
  </data>
<row>

I'm currently using SimpleXML to try to build this, but I'm not sure how to go about inserting the existing XML into the new XML document I'm trying to build.

If there are other standard XML builders that come with PHP, I'm open to using those, too. String concatenation is not an acceptable answer.

Edit: It looks as though SimpleXML won't do what I need. I guess at this point, I need suggestions for other XML parsers.

like image 316
haydenmuhl Avatar asked Nov 05 '22 05:11

haydenmuhl


1 Answers

$xml = new SimpleXMLElement('<row></row>');
$xml->addChild('id', /*database ID column*/);
$xml->addChild('name', /*database Name column*/);

$data = new SimpleXMLElement(/*database Data column*/);

$xml->addChild('data');
$xml->data->addChild('foo', $data->foo);
$xml->data->addChild('bar', $data->bar);

Tested and it works. It should be trivial to convert this to your actual application. There may be a more flexible way of doing it, but I'm not aware of it. They don't call it SimpleXML for nothing :)

like image 88
Jonah Avatar answered Nov 09 '22 08:11

Jonah