写入文件会在行尾添加奇怪的内容

时间:2014-10-28 03:43:55

标签: php xml

我正在开发一个程序来解析用户上传的文本文件,然后将解析后的XML文件保存在服务器上。但是,当我编写XML文件时,我得到了一些文本



在每一行的末尾。此文本不在我的原始文本文件中。在我打开新的XML文件以验证它是否正在修复所有内容之前,我甚至没有注意到它。有没有人遇到过这个问题,如果是这样的话,你能告诉我这是因为我创建和编写文件的方式吗?

fileUpload.php - 当用户上传文件时会出现这3行。

$fileName = basename($_FILES['fileaddress']['name']);
$fileContents = file_get_contents($_FILES['fileaddress']['tmp_name']);
$xml = $parser->parseUnformattedText($fileContents);
$parsedFileName = pathinfo($fileName, PATHINFO_FILENAME) . ".xml";
file_put_contents($parsedFileName, $xml);

parser.php

function parseUnformattedText($inputText, $bookName = "")
{
   //create book, clause, text nodes
   $book = new SimpleXmlElement("<book></book>");
   $book->addAttribute("bookName", $bookName);

   $conj = $book->addChild("conj", "X");

   $clause = $book->addChild("clause");

   $trimmedText = $this->trimNewLines($inputText);
   $trimmedText = $this->trimSpaces($inputText);
   $text = $clause->addChild("text", $trimmedText);
   $this->addChapterVerse($text, "", "");

   //make list of pconj's for beginning of file
   $pconjs = $this->getPconjList();

   //convert the xml to string
   $xml = $book->asXml();   

   //combine the list of pconj's and xml string
   $xml = "$pconjs\n$xml";
   return $xml;
}

输入文字文件

1:1 X
it seemed good to me also,
X
having had perfect understanding of all things from the very first
to write you an orderly account, [most] excellent Theophilius
and
1:4
that
you may know the certainty of those things in which you were instructed

1:5 X
There was in the days of Herod, the king of Judea and a certain priest named Zacharias
X
his wife[was] of the daughters of Aaron
and
her name [was] Elizabeth.
1:8 So
it was,
that
while he was serving as priest 1:9 before God in the order of his division,
1:10 and
the whole multitude of the people was praying outside at the hour of incense
but
therefore
it was done.

2 个答案:

答案 0 :(得分:0)

&#xD;\r\n的ASCII字符,似乎无法从parseUnformattedText()正确显示。

尝试$xml = nl2br($parser->parseUnformattedText($fileContents));

答案 1 :(得分:0)

关于Seroczynski的回答,我能够创建一个修剪过的函数,从文本中删除任何回车符。之后XML输出看起来很好。这是我用来解决问题的功能:

function trimCarriageReturns($text)
{
   $textOut = str_replace("\r", "\n", $text);
   $textOut = str_replace("\n\n", "\n", $textOut);
   return $textOut;
}