Extract information from some lines of a CSV file with PHP - 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);

Related

Reading and parsing english with japnese characters from a cav file php

i have a csv file which have lots of lines like this:
I Want It All (Tribute to Queen);Dancer (おもしろ♪ Ver.)
Hijo De La Luna (Tribute to Mecano);Perfect (おもしろ♪ Ver.)
You've Got A Friend In Me (おもしろ♪英語 Ver.) [映画『トイ·ストーリー』より]
The CSV file has two columns. First one contains only english strings but 2nd one contains mix of english and japnese characters. My code to read this csv file:
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<?php
header('Content-Encoding: UTF-8');
$string = file_get_contents('myfile.csv');
echo $string;
?>
// My output
��I Want It All (Tribute to Queen);Dancer (J0�0W0�0j& Ver.)
Hijo De La Luna (Tribute to Mecano);Perfect (J0�0W0�0j& Ver.)
��You've Got A Friend In Me (J0�0W0�0j&񂞊 Ver.) [ f;u0�0�0��0�0�0�0�00�0�0]
If I try:
echo "Losing My Religion (Tribute to R.E.M.);I Love It (オモシロ♪ヴォイス ver.)"
it displays text with japnese characters correctly. I tried all the solutions, i found on this site, but unable to parse the csv file correctly.
I need help to parse this file correctly. Thanks in advance for your help!
I got the issue solved by this:
$f = file_get_contents('myfile.csv'); // Get the whole file as string
$f = mb_convert_encoding($f, 'UTF8', 'UTF-16LE'); // Convert the file to UTF8
$f = preg_split("/\R/", $f); // Split it by line breaks
$f = array_map('str_getcsv', $f);

PHP translating via csv file

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

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

PO files translations: going backwords, from msgstr to msgid?

I'm in need to start from the msgstr to retrieve the msgid. The reason is that I've got several translations, all EN to SOME OTHER LANG, but now in the current installation I need to go back from SOME OTHER LANG to EN. Note that I'm also working in WordPress, maybe this is not important though. There are a couple of similar questions here but not exactly what I need.
So is there a way to accomplish this?
WordPress ships with a PO reader and writer as part of the pomo package. Below is a pretty simple script that swaps the msgid and msgstr fields around and writes out a new file.
As already pointed out in the comments, there are several things that make this potentially problematic:
Your target strings must all be unique (and not empty)
If you have message context, this will stay in the original language.
Your original language must have only two plural forms.
Onward -
<?php
require_once 'path/to/wp-includes/pomo/po.php';
$source_file = 'path/to/languages/old-file.po';
$target_file = 'path/to/languages/new-file.po';
// parse original message catalogue from source file
$source = new PO;
$source->import_from_file($source_file);
// prep target messages with a different language
$target = new PO;
$target->set_headers( $source->headers );
$target->set_header('Language', 'en_US');
$target->set_header('Language-Team', 'English from SOME OTHER LANG');
$target->set_header('Plural-Forms', 'nplurals=2; plural=n!=1;');
/* #var Translation_Entry $entry */
foreach( $source->entries as $entry ){
$reversed = clone $entry;
// swap msgid and msgstr (singular)
$reversed->singular = $entry->translations[0];
$reversed->translations[0] = $entry->singular;
// swap msgid_plural and msgstr[2] (plural)
if( $entry->is_plural ){
$reversed->plural = $entry->translations[1];
$reversed->translations[1] = $entry->plural;
}
// append target file with modified entry
$target->add_entry( $reversed );
}
// write final file back to disk
file_put_contents( $target_file, $target->export() );

Dealing with line breaks in individual cells in a CSV file

I'm currently working on a webapplication that will take the data from a CSV file, and convert it into an array for easier access to specific data in the file. I do however have a problem. Currently my code looks something like this:
$data = file_get_contents('data.csv');
$array = str_getcsv($data,"\n");
$i = 0;
foreach($array as $row){
$newArray[$i] = str_getcsv($row,";");
$i++;
}
This works fine for the most part, but it messes up when there is a line break inside an individual value. I'm working with product descriptions so some of the companies put intentional line breaks in their descriptions. When I open the file in Excel I can see these linebreaks clearly, and my question is now, how do I deal with them? I've tried a lot of different approaches and read a lot online, but nothing seems to work for me.
I hope you can help me find a solution.
EDIT
Here is an example from the CSV file
5124;"Altid billig el og 5 stjerner på Trustpilot";"Altid billig el og 5 stjerner på Trustpilot.#
Vi har kun ét produkt og du skal ikke længere spekulere i om du nu har en billig elleverandør efter 6 måneder eller lign. Vi går efter at være blandt de billigste elleverandører, hvilket vi også beviser hvert år."
I don't know if it makes much sense, but this where the problem is. In this particular exampel there is a "forced" line break when I open it in excel, where i placed a bold "#". As far as I can see this should be valid?
str_getcsv expects one row of CSV formatted text, you cannot use it to parse an entire file. Let fgetcsv read and parse the file line by line:
$file = fopen('data.csv', 'r');
$data = [];
while ($row = fgetcsv($file)) {
$data[] = $row;
}
fclose($file);
var_dump($data);

Categories