rsmarsha
rsmarsha

Reputation: 368

need to add carriage returns after each xml element (php)

I have a file that is sent over https and I am handling with a php script.

The data is accepted using:

$data = file_get_contents('php://input')

If written to a file it is written as one line.

Due to our internal systems (IBM power 7) I'm told by I.T that I need to add a carriage return after each xml element.

So the file currently opens in an editor as :

<root><element1><element2></element2></element1></root>

I need it to be :

<root>
<element1>
<element2></element2>
</element1>
</root>

Which requires inserting "\n" after each closing tag and a tag with children.

Any ideas?

Upvotes: 0

Views: 1913

Answers (2)

ceving
ceving

Reputation: 23824

The formatOutput option will do it.

Upvotes: 2

Kaii
Kaii

Reputation: 20540

If it's just for inserting line-breaks, a regex will do fine.

However, do NOT start parsing XML with Regular Expressions!

Try this:

$xml = preg_replace(
         '=(<(.*?)>)(?![^<>]*</\2>|$)=s', 
         "\\1\n", 
         file_get_contents('php://input') ); 

The expression matches all XML tags that are not followed by EOF or a matching closing tag using a negative lookahead assertion [(?!..)] and a backreference.

Upvotes: 2

Related Questions