PHP translating via csv file - php

I have written a small PHP function to read a CSV file as source of Language(s).
class getLang {
var $lang;
function __construct() {
$theBigArray = file('/inc/lang.csv');
foreach ($theBigArray as $key => $value) {
$line = explode(',', $value);
$this->lang[trim($line[0])] = trim($line[1]);
}
}
}
Imagine the CSV file has a content like this :
Hello , Hallo
goodbye , Vaarwel
pizza , pizza
food , voedsel
morning , ochtend-
thanks, dank je
morning , Goedemorgen
nice , Leuk je te zien
day , goedendag
...
last_word , laatste woord
It's working well, for what I need, but I'm looking for a better idea to read CSV file and return a simple array or an object.
Note : Regarding, such CSV file will be filled out by a person(s) who don't know the programming and mostly, they use MS Excel to fill/make the CSV file, But we not talking about Regular expression in this post.
Best regard

Related

Trying to read a csv file with thailand's character in it using php but after reading it the characters are changed to some unidentified characters

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);

Extract information from some lines of a CSV file with PHP

I am trying to extract some information from a csv file. What I want is to extract information only from the lines where this information is from the email and ID.
Previously I had no problems extracting information from csv files via php, however this csv file that I am using has the information in a very particular way.
Here I show part of the contents of the csv file:
As you can see, the information entered is not in a conventional format.
Using this small code:
$file = fopen("mails.csv","rb");
while(feof($file) == false)
{
echo fgets($file). "<br />";
}
fclose($file);
I get this on screen:
the file is more extensive, has more data. What I have shown is only a small part of the file, used as an example.
What I want to do is extract information from the lines where the radio type input is because there is the email, which is the information that I really want to extract.
I have tried with the conventional PHP functions to extract information from csv files but they do not work for me.
they throw me multiple errors and I can not get the information only from the lines that have the emails and save those emails in an array.
Alguna idea que puedan darme para obtener solo las lineas que tienen los inputs radio y extraer de allí el correo electronico de cada linea y guardarlo en un array?
Any help they can give me I would appreciate it.
Assuming that your format never changes (including for the invalid lines that you wish to ignore), the below would work.
Note: I have not tested this code so use this as a pointer and make adjustments as required.
$file = fopen("mails.csv","rb");
while(feof($file) == false){
$contents = fgets($file);
if (substr($contents,0,1) != "#"){
$val = explode(",", $contents);
echo $val[0]. "<br />";
}
}
fclose($file);

Search a string in a CSV file , output all the lines which contain it as table - PHP

I am new to the world of coding and learning PHP these days. For almost one week of research on this issue , I have almost given up on this issue. Hope to get some good insight on it from the experts.
Problem :- I have a CSV file which has information about servers. for Example :
ClientId,ProductName,Server,ServerRole,Webserver,DatabaseName
001,abc,Server1,Web,Webserver1,,
001,abc,Server2,Dabatase,,Database1
001,abc,Server3,Application,,,
002,abc,Server4,Web,Webserver2,,
002,abc,Server5,Database,,Database2,
I created a HTML page which has a simple html form which takes a server name as an input and invokes the commands written in a page called "search.php". I am able to save the user input from index form to a variable fine . But here is the real problem. I want to search that variable against this CSV file , find the client name ( column 1) related to that server ( which should be matched from column 3 ) and then , print all the lines for that client. For e.g. if I input "Server3" , I should get the first three lines as output in a table form.
I have used fgetcsv() , fgets() etc. but I dont seem to crack this. So far , the closest I have reached is printing all the lines which contain the input text (and that too not in a table form). Any help to resolve my problem would be much appreciated.
Here is my code so far:
<?php
$name = $_POST["search"];
echo "You have searched for the server <b>$name</b>";
$output = "";
$fp = fopen("D:\VMware\DSRM\Servers\Servers.csv", "r");
// Read file
$txt = fgets($fp);
while ( !feof( $fp ) ) {
// Search for keyword
if ( stripos( $txt, $name ) !== false ) {
$output .= $txt.'<br />';
}
$txt = fgets($fp);
}
echo $output;
?>
What about regex?
$input_lines = file_get_contents("theCSV");
$server = "Server3";
preg_match_all("/(\d+).*(".$server.")(.*)/", $input_lines, $clientid);
preg_match_all("/(". $clientid[1] .".*)/", $input_lines, $output_array);
Var_dump(output_array[1]);
In theory this should work :-)

php explode() storing all values from test filt to index [0]

I am a student, currently learning PHP and having a tough time getting the explode() function to work the way I want.
The following text file "vacations.txt" contains:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano"
"87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony Cancun Jamaica etc."
"09876", "Rome and Madrid", "3999.00", "I see Italy I see Spain"
"32198", "Ski Tahoe", "1200.00", "Ski all day Gamble all night"
I have tried to put this into an array delimited by the comma. Using print_r(), I can see that it's all going into the first index of my array.
Here's my code:
function displaySpecials() {
$prodString = include("vacation.txt");
$vacArray = explode(',', $prodString );
print_r($vacArray);
}
Here is the output:
"54321", "Big Island Hawaii", "2999.00", "Best beaches big volcano"
"87654", "Cruise Caribbean", "3500.00", "Ocean view with balcony
Cancun Jamaica etc." "09876", "Rome and Madrid", "3999.00", "I see
Italy I see Spain" "32198", "Ski Tahoe", "1200.00", "Ski all day
Gamble all night"Array ( [0] => 1 )
I have searched, and read everything I can find about explode(), but I cannot figure out why this is happening. My end goal is to output a multidimentional array in a table with 4 rows and 4 columns to display the 16 values in the text file.
All help is greatly appreciated. Thank you in advance!
The include statement includes and evaluates the specified file.
include will evaluate whatever is in it, basically to include other php script.
You need to fetch its content.
Below I have used file to fetch contents of file linewise.
function displaySpecials() {
$lines = file("vacation.txt"); // will return lines in array
foreach($lines as $line){ // loop for each line
$vacArray[] = explode(",", $line); // insert resulting array to last index of $varArray
}
print_r($vacArray);
return $vacArray;
}
Also, the file appears to be regular .csv you can use fgetcsv. Check the example in the official docs.
Since this is basically a csv file, I'd recommend using fgetcsv, something like this:
if (($h = fopen('vacation.txt', 'r')) !== false) {
while (($data = fgetcsv($h, 1000, ',')) !== false) {
// Fetch the data here
}
}
Optionally, you can also use str_getcsv:
$data = array_map('str_getcsv', file('vacation.txt'));
Try to replace include("vacation.txt") with file_get_contents("vacation.txt").
include
The include statement includes and evaluates the specified file.
file_get contents
Reads entire file into a string
Your code should look like this:
function displaySpecials() {
$prodString = file_get_contents("vacation.txt");
$vacArray = explode(',', $prodString );
print_r($vacArray);
}

Fill form with fpdm.php doesn't work with select value

this is my first question ever.
I have a form pdf that i need to fill with php, it works fine with fpdm. When I open the file in chrome or in Architect 4 even the dropdown list are filled but when I open the same file in Adobe Reader, everything is filled except the dropdown list.
Anyone have any thoughts about it ? I think maybe it's a conversion problem between FDF and PDF but i have really no idea on how to solve it.
EDIT :
$fieldsI = array(
/* ---------------- Beneficiaire 1 ----------------*/
'ZA1benefNom1' => $InfosFormateur[0]['nom'],
'ZA1benefPrenom1' => $InfosFormateur[0]['prenom'],
[...]
'ZA4nature1' => 'H ', //strval('H'),
'ZA4montant1' => strval($montant[$InfosFormateur[0]['IdProfil']])
);
$pdf = new FPDM('pdf/das2/form2.pdf');
$pdf->Load($fieldsI, true); // second parameter: true if UTF-8
$pdf->Merge();
I don't know where i can upload the result.
I have an other problem by the way, when I want to merge all my pdf filled, i try many solutions. I have one almost working :
public function combine_pdf($outputName,$fileArray)
{
$merged_pdf = "";
foreach($fileArray as $filename){
$merged_pdf .= " ".$filename;
}
exec("pdftk".$merged_pdf." cat output ".$outputName);
header(sprintf('Location: %s', $outputName));
}
But when i open the pdf generated in Adobe Pdf reader, everything is blank again.
I have found the solution. It's working !
You need pdftk on your server :
public function combine_pdf($outputName,$fileArray, $rep = "download/DAS/")
{
$merged_pdf = "";
foreach($fileArray as $filename){
$merged_pdf .= " ".$filename;
}
exec("pdftk".$merged_pdf." cat output ".$rep."tmpfinal.pdf "); //merge all my filled pdf to 1 pdf
exec("pdftk ".$rep."tmpfinal.pdf generate_fdf output ".$rep."final.fdf"); //generate a clean fdf from this pdf
exec("pdftk ".$rep."tmpfinal.pdf fill_form ".$rep."final.fdf output ".$outputName); // then use the pdf as template filled by the fdf.
header(sprintf('Location: %s', $outputName));
}
I hope it will help someone

Categories