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().

2 Answers 2

1

Use SimpleXML:

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

foreach($root as $child)
    $arrXml[] = $child->asXml();
Sign up to request clarification or add additional context in comments.

3 Comments

When I run this code with: "<root><node attr='test'>123</node><node2><t>2</t></node2></root>" I get this: ["123<\/node>","2<\/t><\/node2>"], so without the first <node>?
@Anorionil When you output xml in browser don't forget about htmlspecialchars because xml nodes will be treated as HTML code...
Ahh thank you! It was working all along, I just didn't see it :/ Dumb :(
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;
}

2 Comments

There's no \n between the different lines I'm afraid. I added the line breaks just to make my example a bit more readable.
well than you should have mentioned that in your question :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.