【问题标题】:writing special characters to txt file将特殊字符写入txt文件
【发布时间】:2012-03-11 10:20:26
【问题描述】:

我正在从远程文件中读取一些数据,直到我将一些特定行写入文本文件时,一切都正常工作。
这里的问题是,当我写类似 Girl's Goldtone 'X' CZ Ring 之类的东西时,它会变成 Girl & apos;s Goldtone &apos ;X & apos; txt 文件中的 CZ 环
我如何写入 txt 文件,以便它保留上面写的文本而不显示字符代码而是实际字符。
我的代码示例。

$content_to_write = '<li class="category-top"><span class="top-span"><a class="category-top" href="'.$linktext.'.html">'.$productName.'</a></span></li>'."\r\n";
                fwrite($fp, $content_to_write);  
$linktext = "Girls-Goldtone-X-CZ-Ring";  
$productName = "Girl's Goldtone 'X' CZ Ring";  

var_dump

string '<li class="category-top"><span class="top-span"><a class="category-top" href="Stellar-Steed-Gallery-wrapped-Canvas-Art.html">&apos;Stellar Steed&apos; Gallery-wrapped Canvas Art</a></span></li>

'(长度=195)

代码

                $productName =$linktext;


                $linktext = str_replace(" ", "-", $linktext);
                $delChar = substr($linktext, -1);
                if($delChar == '.')
                {
                    $linktext = substr($linktext, 0, -1);
                }

                $linktext = removeRepeated($linktext);
                $linktext = remove_invalid_char($linktext);
                $productName = html_entity_decode($productName);
                $content_to_write = '<li class="category-top"><span class="top-span"><a class="category-top" href="'.$linktext.'.html">'.$productName.'</a></span></li>'."\r\n";
                var_dump($content_to_write);
                fwrite($fp, utf8_encode($content_to_write));

【问题讨论】:

  • 这只是一个编码问题。外部文件使用哪种编码,查看输出时使用哪种编码,写入.txt文件时使用哪种编码?

标签: php


【解决方案1】:

fwrite 是二进制安全的,这意味着它不做任何编码工作,而只是将您提供的任何内容直接写入文件。看起来您正在编写的 $productName 变量在编写之前已经进行了实体编码。尝试先在变量上运行html_entity_decode

注意html_entity_decode 默认不接触单引号(&amp;apos;);您必须在第二个参数中设置 ENT_QUOTES 标志。您可能还想在第三个参数中明确指定编码。

【讨论】:

  • 对不起,我更正了 $productName。但我的变量从数组中获取值。这是我从远程文件中读取的随机行。浏览器上的一切似乎都很好,但在 txt 中问题仍然存在。
  • 是的,我已经尝试了大约 2 天了。但似乎没有任何效果。是平台问题还是什么,我在win 7 64bit,WAMP。它与它有什么关系吗?
  • @MuhammadIrfan:您能否向我们展示您正在使用的实际代码以及您正在编写的数据的var_dump()(就在实际编写之前)?
  • @MuhammadIrfan:查看我更新的答案,修改引号模式是否可以解决问题?
  • 仍然没有变化,我什至看不到 txt 文件上的任何编码。如何确保用 fwrite 编写的 txt 文件被编码。
【解决方案2】:

您是从远程文件读取数据,然后将其写入 txt 文件吗?同意上面的评论,这是编码的问题。试试下面的代码:

$file = file_get_contents("messages.txt");
$file = mb_convert_encoding($file, 'HTML-ENTITIES', "UTF-8");
echo $file;

将响应回显到您的浏览器并查看。如果发现正确,请将响应写入您的 txt 文件。确保您的 txt 文件是 UTF8 编码的。

看看这个::Write Special characters in a file.

【讨论】:

  • 谢谢,但我没有解决问题。我正在从 url 读取一个 txt 文件,然后通过 fgets 读取一个随机行,此行在浏览器上显示正确,但是当我通过 fwrite 将此行写入 txt 时,它搞砸了所有特殊字符。
猜你喜欢
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-29
  • 2018-05-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多