开发者

How to properly add newlines to an XML string in PHP?

开发者 https://www.devze.com 2022-12-29 17:30 出处:网络
I have some xml that I manually construct in a function that is something like: $xml = \"<myxml>\";

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 .= "</my开发者_C百科xml>";

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?


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;


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


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 .../>.


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


You can write you XML like this,

$xml = <<<XML
<myxml>
 ...
</myxml>
XML;
0

精彩评论

暂无评论...
验证码 换一张
取 消