1

我知道这可能是一个非常简单的问题,但我仍然没有找到解决方案......好吧,我会简短:假设有一个如此结构化的 XML 文件:

<root><item><text>blah blah blah&#xD;blah blah blah&#xD;blah blah blah&#xD;...</text></item></root>

我的 XML 显然更复杂,但这并不重要,因为我的问题是:如何&#xD;用例如 html<br>标记替换它们?

我正在使用 SimpleXML 从 XML 读取数据并尝试使用:

echo str_replace("&#xD;", "<br>", $message->text);

甚至:

echo str_replace("\n", "<br>", $message->text);

但没有...

我需要为此使用 SimpleXML。

4

2 回答 2

7

&#xD; represents the ASCII "carriage return" character (ASCII code 13, which is D in hexadecimal), sometimes written "\r", rather than the "linefeed" character, "\n" (which is ASCII 10, or A in hex). Note that when SimpleXML is asked for the string content of a node (with (string)$node or implicitly with statements like echo $node) it will turn this "entity" into the actual character it represents.

Depending on your platform (Windows, Linux, MacOS, etc), the standard line-ending, accessible via the built-in constant PHP_EOL, will be either "\n", "\r\n", or "\r".

The safest way to replace these with HTML linebreak tags (<br>) is to replace any of these characters, since you don't know which convention the source of the XML data might have been using.

PHP has a built-in function which should be able to do this for you, called nl2br(). If you want a slightly custom version, there's a comment in the docs from "ngkongs" showing how to use str_replace to similar effect.

于 2013-03-30T19:24:57.237 回答
1

我在发布我的问题之前想出了如何解决,所以,已经写了,我会分享这个希望它迟早对其他人有用......

这可以解决问题:

echo str_replace(PHP_EOL, "<br>", $message->text);
于 2013-03-30T09:29:28.340 回答