I am having issues reading-writing data(with special-characters) to file.
I am doing something like this:
//Writing data..
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'filename.db';
$data = 'Some string with special characters';
//Writing to the file..
#file_put_contents($file, json_encode($data));
?>
This works fine.
When I open the db file in Notepad ++, the data is proper.
Special characters are also stored properly:
//Reading data..
<?php
header('Content-Type: text/html; charset=utf-8');
$file = 'filename.db';
//Reading from the file..
$data = file_get_contents($file);
$data = json_decode(utf8_encode(stripslashes($data)));
echo $data;
?>
This displays the special characters as "????" or sometimes like "u00cf" or some other characters.
What is going wrong, and where?
Any help would be appreciated,
Thanks.
If you're not storing arrays or other complex data structures you do not need JSON.
When reading from the file, why in god's name do you mistreat the data by stripping slashes and running it through utf8_encode? That's what's destroying the JSON format and thereby your data.
Just write the raw string into a file and read it back as is, done!
$string = 'ユーティーエッフエイト';
file_put_contents('file.txt', $string);
$string = file_get_contents('file.txt');
Nothing more you need to do.
In data reading script, try:
$data = json_decode(mb_convert_encoding(stripslashes($data),
"UTF-8"));
Related
I have a csv file that have data like this:
Sub District District
A Hi อาฮี Tha Li District ท่าลี่
A Phon อาโพน Buachet District บัวเชด
when I tried to read it using php code by following this SO question:
<?php
//set internal encoding to utf8
mb_internal_encoding('utf8');
$fileContent = file_get_contents('thai_unicode.csv');
//convert content from unicode to utf
$fileContentUtf = mb_convert_encoding($fileContent, 'utf8', 'unicode');
echo "parse utf8 string:\n";
var_dump(str_getcsv($fileContentUtf, ';'));
But it didn't work at all. Someone please let me know what I am doing wrong here.
Thanks in advance.
There are 2 issues with your code:
Your code applies str_getcsv to whole file contents (instead of individual line)
Your code example is using delimiter ";" but there is no such symbol in your input file.
Your data is in either fixed field length format (which is actually not a csv file) or in tab delimited csv file format.
If it is tab delimited file format then you can use 2 ways to read your file:
$lines = file('thai_unicode.csv');
foreach($lines as $line){
$data = str_getcsv($line,"\t");
echo "sub_district: ". $data[0].", district: ".$data[1]."\n";
}
or
$f = fopen('thai_unicode.csv',"r");
while($data = fgetcsv($f,0,"\t")){
echo "sub_district: ". $data[0].", district: ".$data[1]."\n";
}
fclose($f);
And in case you have fixed length fields data format you need to split each line yourself because csv related php function are not suitable for this purpose.
So you will end up with something like this:
$f = fopen('thai_unicode.csv',"r");
while($line = fgets($f)){
$sub_district = mb_substr($line,0,20);
$district = mb_substr($line,20);
echo "sub_district: $sub_district, district: $district\n";
}
fclose($f);
I'm trying to open and show a nfo file with a php script.
Everything is working but the result isn't like in the NFO file. I got special chars like that :
�������������������������
When I open the source code of the result, I can see the NFO file like he is in real!
Did I need to use some special tricks for HTML or something like that ?
You can convert the character encoding of your NFO text (to output to eg. utf8):
$nfoContent = file_get_contents('foo.nfo');
$nfoContent = mb_convert_encoding($nfoContent, 'UTF-8', 'ASCII');
Thanks for your reply!
I found it, in PHP you just need to do :
header('Content-Type: text/plain; charset=ansi');
<?php
header('Content-Type: text/html; charset=UTF-8');
$file = 'CORE.NFO';
$nfo = file_get_contents($file);
echo '<pre>';
echo iconv('CP850', 'UTF-8', $nfo).PHP_EOL;
echo '</pre>';
http://pastebin.com/uqxg4yYC
CP850 west europe
CP866 russia
https://de.wikipedia.org/wiki/NFO
I'm relatively new to PHP and I'm trying to get a small script running. I have a VB .net program that posts data using the following function.
Public Sub PHPPost(ByVal User As String, ByVal Score As String)
Dim postData As String = "user=" & User & "&" & "score=" & Score
Dim encoding As New UTF8Encoding
Dim byteData As Byte() = encoding.GetBytes(postData)
Dim postReq As HttpWebRequest = DirectCast(WebRequest.Create("http://myphpscript"), HttpWebRequest)
postReq.Method = "POST"
postReq.KeepAlive = True
postReq.ContentType = "application/x-www-form-urlencoded"
postReq.ContentLength = byteData.Length
Dim postReqStream As Stream = postReq.GetRequestStream()
postReqStream.Write(byteData, 0, byteData.Length)
postReqStream.Close()
End Sub
Where "myphpscript" is acutally the full URL to the PHP script. Basically I'm trying to POST the "User" variable and the "Score" variable to the PHP script. The script I've tried is as follows:
<?php
$File = "scores.rtf";
$f = fopen($File,'a');
$name = $_POST["name"];
$score = $_POST["score"];
fwrite($f,"\n$name $score");
fclose($f);
?>
The "scores.rtf" does not change. Any help would be appreciated. Thanks ahead of time, I'm new to PHP.
Ensure that your script is receiving the POST variables.
http://php.net/manual/en/function.file-put-contents.php
You can try file_put_contents, it combines the use of fopen ,fwrite & fclose.
It could be wise to use something like isset/empty to check that there is something to write before writing.
<?php
$file = 'scores.rtf';
// Open the file to get existing content
$current = file_get_contents($file);
// Append a new person to the file
$current .= print_r($_POST);
//Once confirmed remove the above line and use below
$current .= $_POST['name'] . ' ' . $_POST['score'] . "\n";
// Write the contents back to the file
file_put_contents($file, $current);
?>
Also, totally overlooked the RTF part, definitely look into what Mahan mentioned. I'd suggest the above if you have no need for that specific file type.
The "scores.rtf" does not change.
well RTF files is handled differently because its not really a pure text file it contains meta-data and tags that controls how text is displayed on the rtf file. please have a time to read to the following sources
http://www.webdev-tuts.com/generate-rtf-file-using-php.html
http://b-l-w.de/phprtf_en.php
http://paggard.com/projects/doc.generator/doc_generator_help.html
if in any case you want a normal text file you can use the code below, don't use fwrite(), please use file_put_contents()
file_put_contents("scores.txt", "\n$name $score");
I'm trying to write some php-code that takes $_GET-data as an input and saves it into a csv-file.
When running the code more than once my csv-file looks like this:
Date,Time,Temperature,"Air Humidity","Soil Humidity",Light,"Wind Direction","Wind Speed",Rain
2013-03-16,16:24:27,12,80,40,82,255,10,0
"2013-03-16,16:24:26,12,80,40,82,255,10,0
","""2013-03-16,16:24:26,12,80,40,82,255,10,0
",""",""""""2013-03-16,16:24:25,12,80,40,82,255,10,0
",""","""""",""""
",""",""""""
","""
"
As you can see, the program adds quotation marks and commas into my data that I don't want. This is apparently done by 'file("weather_data.csv")' but I don't know how to disable or work around this.
This is my code for now:
<?php
// Save received data into variables:
$temperature = $_GET["t"];
$airHumidity = $_GET["ha"];
$soilHumidity = $_GET["hs"];
$light = $_GET["l"];
$windDir = $_GET["wd"];
$windSpeed = $_GET["ws"];
$rain = $_GET["r"];
// Arrays for the column descriptor (first line in the csv-file) and the recent data:
$columnDescriptor = array("Date","Time","Temperature","Air Humidity","Soil Humidity","Light","Wind Direction","Wind Speed","Rain");
$recentData = array(date("Y-m-d"),date("H:i:s"),$temperature,$airHumidity,$soilHumidity,$light,$windDir,$windSpeed,$rain);
$fileContents = file("weather_data.csv");
array_shift($fileContents); // removes first field of $fileContents
$file = fopen("weather_data.csv","w");
fputcsv($file,$columnDescriptor);
fputcsv($file,$recentData);
fputcsv($file,$fileContents);
fclose($file);
?>
$fileContents is read as an array of strings, one entry per line of the CSV file but the actual CSV data is not parsed. The last fputcsv tries to write this data as CSV and escapes it (adding quotes and stuff). You need to add the old file contents ($fileContents) to your file with fwrite instead of fputcsv:
fwrite($file, implode("\n", $fileContents));
I am reading some data from a remote file, got every thing working till the point when i write some specific lines to a text file.
problem here is, when i write something like Girl's Goldtone 'X' CZ Ring it becomes Girl & apos;s Goldtone &apos ;X & apos; CZ Ring in txt file.
how do i write to txt file so that it retains text like written above and not show character code but actual character.
sample of my code.
$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">'Stellar Steed' Gallery-wrapped Canvas Art</a></span></li>
' (length=195)
Code
$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));
Is it that you are reading the data from a remote file and then writing the same to a txt file? Agree with the above comment, its an issue with encoding. Try the following code:
$file = file_get_contents("messages.txt");
$file = mb_convert_encoding($file, 'HTML-ENTITIES', "UTF-8");
echo $file;
echo the response to your browser and see. If found proper, write the response to your txt file. Ensure that your txt file is UTF8 - encoded.
Check this out:: Write Special characters in a file.
fwrite is binary-safe, meaning it doesn't do any encoding stuff but just writes whatever you feed it directly to the file. It looks like the $productName variable you're writing is already entity-encoded before writing. Try running html_entity_decode over the variable first.
Note that html_entity_decode doesn't touch single quotes (') by default; you'll have to set the ENT_QUOTES flag in the second parameter. You might also want to explicitly specify an encoding in the third parameter.