user1015214
user1015214

Reputation: 3081

Using php's SimpleXMLItterator to print sub elements in order

I am dealing with the following XML:

<Paragraph>This is a test. This is a test.
<Italic>This is an italicized test</Italic>
This is more tests
 </Paragraph>

I'm trying to pull in the XML, modify it as a text string or HTML code, and spit it back out. I'm running into the issue that I see no way of keeping all this text in its correct order. This is my code:

$xml = "<Paragraph>This is a test. This is a test.
<Italic>This is an italicized test</Italic>
This is more tests
 </Paragraph>";
$itterator = new SimpleXmlIterator($xml);
$non_italicized = $itterator->__toString();
for ($itterator->rewind(); $itterator->valid(); $itterator->next()) {
  $italicized = $itterator->current()->__toString();
}

The output of $non_italicized:

 This is a test. This is a test.
 This is more tests

The output of $italicized:

This is an italisized test

This leaves me no real of way of combinging them together in a regular paragraph with italicized text in the middle. How can I achieve this?

Upvotes: 0

Views: 35

Answers (1)

VolenD
VolenD

Reputation: 3692

You can do this with DOM:

$doc = new DOMDocument();
$doc->loadXML($xml);

foreach ($doc->childNodes->item(0)->childNodes as $i) {
    echo "Element is: " . $i->nodeName . " Value is: " . trim($i->nodeValue) . "\n";
}

The output will be:

Element is: #text Value is: This is a test. This is a test.
Element is: Italic Value is: This is an italicized test
Element is: #text Value is: This is more tests

However, it will be easier if the regular text is enclosed in some tags.

Upvotes: 2

Related Questions