1

I'm trying to split an XML string, like this:

<root>
  <item attr='test'>test1</item>
  <anotherItem>test2</anotherItem>
  <item3><t>Title</t><foo></foo></item3>
</root>

I want the array to look like:

$arrXml[0] = "<item attr='test'>test1</item>";
$arrXml[1] = "<anotherItem>test2</anotherItem>";
$arrXml[2] = "<item3><t>Title</t><foo></foo></item3>";

I already looked at the solutions in Split XML in PHP but they only work for an XML document with only "item" nodes.

I've tried using XmlReader but after I use read(), how can I get the current node including its own xml with attributes? readOuterXml() doesn't seem to work and only outputs the inner value.

The xml doesn't contain \n so I can't use explode().

Community
  • 1
  • 1
Anorionil
  • 505
  • 2
  • 7
  • 17

2 Answers2

1

Use SimpleXML:

$root = simplexml_load_string($xml);
$arrXml = array();

foreach($root as $child)
    $arrXml[] = $child->asXml();
barell
  • 1,470
  • 13
  • 19
  • When I run this code with: "1232" I get this: ["123<\/node>","2<\/t><\/node2>"], so without the first ? – Anorionil Mar 12 '14 at 13:32
  • 1
    @Anorionil When you output xml in browser don't forget about `htmlspecialchars` because xml nodes will be treated as HTML code... – barell Mar 12 '14 at 13:35
  • Ahh thank you! It was working all along, I just didn't see it :/ Dumb :( – Anorionil Mar 12 '14 at 13:36
0

based on your wished output what you are trying to do is parse string not XML string. you can use regex or simply just explode.

something like:

$lines = explode("\n", $string);
$arrXml = array();
foreach ($lines as $line) {
    $line = trim($line);
    if ($line == '<root>' || $line == '</root>') {
        continue;
    }
    $arrXml[] = $line;
}
gondo
  • 979
  • 1
  • 10
  • 29