Can't save Arabic text from csv to txt file - php

I have a csv file like this:
region_name, city_name, district_name, ppm_value
منطقة, مدينة , حي , 220.92
...
All columns are strings in Arabic, except ppm_value which is a float number. I'm trying to process the csv file and reproduce it in json format. I tried this:
$districts = array();
$fd = fopen('data2.csv', 'r');
while ($row = fgetcsv($fd)) {
$region = $row[0];
$city = $row[1];
$district = new stdClass();
$district->name = "".$row[2];
$district->ppm = $row[3];
//also add region and city to $district
$districts[] = $district;
}
$json1=json_encode($districts);
file_put_contents("text.txt",$json1);
This produces the following:
[{"name":null,"ppm":"220.92","region":null,"city":null}, ... ]
The float is saved correctly, but the Arabic strings are all null. I even tried to save it like this but I got the same result:
$myfile = fopen('text.txt', "w") or die("Unable to open file!");
fwrite($myfile, json_encode($districts));
fclose($myfile);

I know next to nothing about php, but perhaps the problem is that your arabic text is being encoded as ASCII?
try changing it to unicode before you add it to you JSON object, you probably know how to do this better than I do...
string utf8_encode ( string $data )

Related

Incrementing number inside bloc string using fwrite

im creating file retrieving data from mysql database.
$fo = fopen($newName, 'w')or die("can't open file")
After querying db, lets start writing.
<?php fwrite($fo, $row['entetequestionmonochoix']. PHP_EOL);?>
Correspondance to 'entetequestionmultichoix' is the following:
\begin{question}{01}\scoring{b=1,e=0,m=0,V=0}
im facing a small obstacle when generating file.
The while loop allow me to read and then insert but inside the correspondance i need to increment {01} after each loop.
\begin{question} **{01}**\scoring{b=1,e=0,m=0,V=0}
Use str_replace() to replace {01} with a string containing an incrementing variable.
$i = 1;
while ($row = $results->fetch_assoc()) {
$line = str_replace('{01}', sprintf('{%02d}', $i++), $row['entetequestionmonochoix']);
fwrite($fo, $line . PHP_EOL);
}

Compare and display using Php

I am working on a code where i am having a file.txt which is used like a database and i want to search the content on file.txt in any txt file or json file. But the problem is whenever it searches it skips the 1st line.
Below is my code.
<?php
$gameaudiof = fopen("gameaudio.txt", "a");
$lines1 = file("file.txt");
$data2 = $_FILES['data2']['tmp_name'] or exit("Please select the file");
$data3 = file_get_contents($data2);
foreach($lines1 as $line1){
$line1 = trim($line1);
if(strpos($data3, $line1)){
echo $line1;
echo "\n<br>";
fwrite($gameaudiof, $line1);
fwrite($gameaudiof,"".PHP_EOL);}}fclose($gameaudiof); ?>

Join 2 CSV and replace row values in PHP

I have 2 csv:
the first one look like this:
city , text
Seattle , [city] is a [property] in the middle of [county] and have [citizens] citizens
the second one look like this:
city , property , county , citizens
Seattle , City , King County , 608.660
I will that the output look like so:
City , Text
Seattle , Seattle is a City in the middle of King County and have 608.660 citizens.
The Logic is so, combine two csv, read them, if the City name is the same, replace all the strings [value name] present in the first csv under the column "Text" with the value with the same value name present in the csv2.
After replacing the values, the output will be print in a new csv (csv3).
Thanks in advance,
Ivan
This should get you started:
//Create an array of city->template
$handle = fopen("templates.csv", "r");
if($handle === false){
die("Failed to open templates");
}
$templatesArr = array();
while (($data = fgetcsv($handle)) !== FALSE) {
$templatesArr[$data[0]] = $data[1];//Probably don't want to hard code these here
}
fclose($handle);
//Loop through the data populating the templates.
$handle = fopen("data.csv", "r");
if($handle === false){
die("Failed to open template data");
}
$outArr = array();
while (($data = fgetcsv($handle)) !== FALSE) {
$city = $data[0];
$template = $templatesArr[$city];
//Replace template data with csv data.
$template = str_replace(array('city','property','county','citizens'),array($city,$data[1],$data[2],$data[3]),$template);
$outArr[$city] = $template;
}
fclose($handle);
Please note this isn't tested and doesn't do any sanity checking, you'll probably want to tidy it up a bit first.

Cant remove <p> html tags from string using PHP

I have a weird scenario, I just cant get the tags removed from a string in PHP.
Here's what happens, I'm pulling out the data from the database with encoding ASCII
The the string looks like this
<p>Blue Power Waterproof</p>
Now I do the following to decode the entities
html_entity_decode($p->description)
with the following results <p>Blue Power Waterproof</p> I need to remove the tags but the following is not working
strip_tags(html_entity_decode($p->description))
and removeParagraphTags(html_entity_decode($p->description);
function removeParagraphTags($html){
$pattern = "'#<p[^>]*>(\s| ?)*</p>#'";
iconv(mb_detect_encoding($html, "auto"), 'UTF-8', $html);
return preg_replace($pattern, '', $html);
}
I solved this problem by getting all descriptions from the database that were stored with HTML entities, decoded the entities so that the entities are converted to html, and then updated each record with the html and not with the entity, this fixed the problem
$sql = "SELECT * FROM products";
$result= pg_query($conn,$sql);
while ($row = pg_fetch_array($result,null,PGSQL_ASSOC)) {
$name = html_entity_decode($row['name']);
$name = iconv('UTF-8', 'ASCII', $name);
$desc = html_entity_decode($row['description']);
$desc = iconv('UTF-8', 'ASCII', $desc);
$ldesc = html_entity_decode($row['longDescription']);
$ldesc = iconv('UTF-8', 'ASCII', $ldesc);
$up = "UPDATE products SET name='".pg_escape_string($name)."',description='". pg_escape_string($desc)."',\"longDescription\"='".pg_escape_string($ldesc)."' WHERE p_id=".$row['p_id'];
pg_query($conn,$up) OR die(pg_last_error());
}

Opening Text File in PHP update Database

Okay this will be my last post here for today, have asked you guys enougth questions about why my terrible code dosnt work :)
I am trying to run a query to update all values of a column with a text documents contents. My database looks like follows:
Attribute_id | value
64 | Data.txt
109 | other data
64 | Data2.txt
109 | other data
If you look at my script you can see what I am trying to do, for now I am echoing the query the end result is here: http://dev.central-pet-supplies.co.uk/test.php
it is returning
UPDATE mage_catalog_product_entity_text SET value= 'Array' WHERE value = '13685.txt'
however array should be the text files contents
Here is the script:
<?php
mysql_connect ("localhost","cpsdev_mage1","********");
mysql_select_db ("cpsdev_mage1");
$sql = "select value from mage_catalog_product_entity_text WHERE Attribute_id = 64";
$result = mysql_query ($sql) or die($myQuery."<br/><br/>".mysql_error());
while($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
$lines = file('http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);
$query3 = "UPDATE mage_catalog_product_entity_text " . " SET value= '" . $lines . "' WHERE value = '" . $row['value'] . "'";
echo $query3 ."<br>";
}
?>
Edit: changed file to file_get_contents and now working.
file() reads in the entire file with each line as a new entry in an array. Since you don't want that, you can either join the lines together using implode() by putting
$lines = implode( "\n", $lines);
After:
$lines = file('http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);
Or, by using file_get_contents() instead of file(), which will return the entire file's contents as a string, instead of an array:
$lines = file_get_contents( 'http://dev.central-pet-supplies.co.uk/media/import/' . $row['value']);
You dont show where $lines comes from but its an array i assume of lines in the text file. Use something like file_get_contents to get the contents of the text file as a single string instead.

Categories