tags:

views:

158

answers:

5

I have some xml that I manually construct in a function that is something like:

$xml = "<myxml>";
$xml .= "<items>";
$xml .= "<item1>blah</item1>";
$xml .= "</items>";
$xml .= "</myxml>";

When I output the string though I'd like the newlines to be present. How can I add this to the string without affecting a web service accepting the xml? Do newlines in XML even matter?

+1  A: 

no, they are irrelevant outside of text nodes. IE, a newline within the item1 node will be respected

mhughes
+2  A: 

You would add them by doing $xml = "<myxml>\n";, however, they are not necessary at all, since any XML parser will just disregard them.

webdestroya
+1  A: 

You can write you XML like this,

$xml = <<<XML
<myxml>
 ...
</myxml>
XML;
ZZ Coder
+1  A: 

The new lines aren't required but you can use the PHP_EOL constant which is a cross platform way of finding the new line character. i.e.

$xml = "<myxml>".PHP_EOL;
Obsidian
I was not aware of the PHP_EOL constant thanks for the suggestion!
stormist
no problem :) there's all sorts of weird and wonderful things in PHP, if you ever get bored sometime read the manual from end to end.
Obsidian
+1  A: 

If you do not have to worry about the different kinds of line breaks ("\n", "\r\n", "\r") you can simply use a multi-line string literal like e.g.

$xml = '<myxml>
  <items>
    <item1>blah</item1>
  </items>
</myxml>';

or

$xml = <<< EOT
<myxml>
  <items>
    <item1>blah</item1>
  </items>
</myxml>
EOT;

But keep in mind that those documents aren't necessarily equivalent to

<myxml><items><item1>blah</item1></items></myxml>

http://www.w3.org/TR/REC-xml/ says:

2.10 White Space Handling
[...]
An XML processor MUST always pass all characters in a document that are not markup through to the application. A validating XML processor MUST also inform the application which of these characters constitute white space appearing in element content.

A special attribute named xml:space may be attached to an element to signal an intention that in that element, white space should be preserved by applications

Whitespaces can be marked as significant or insignificant and the consumer can more or less choose if it handles them as in-/significant, e.g. via <xsl:strip-space .../>.

VolkerK
Thank you for the very thorough explanation, a very informative answer. (wish I could accept more than one)
stormist