csv file into array , translation system for a site - php

I need help to solve this problem:
I have a csv file like this
hello,ciao
goodbye,arrivederci
as you can see I try to create a translation system for a site
now I want this csv file into an array, the resultant array must be the same of $langArray
<?php $langArray = array([it]=>array([hello]=>ciao,[goodbye]=>arrivederci)); ?>
I already have a solution using a Json file to have an array like this, and is most usefull that a csv file and I can use translation system also with javascript. but I want to know the way to do that with a csv file thank you

For reading a CSV file you should use fopen and fgetcsv, or for the short version str_getcsv (needs current PHP or compat library):
$csv = array_map("str_getcsv", file("it.csv"));
Then building the associative map requires a manual loop:
foreach ($csv as $line)
$translate["it"][ $line[0] ] = $line[1];

You could use explode to split your data once for the new line, then once for the comma, and fill an array with it.
<?php
$translations = array();
$data = 'hello,ciao
goodbye,arrivederci';
$words = explode("\n", $data);
foreach($words as $w) {
$parts = explode(',', $w);
$translations[$parts[0]] = $parts[1];
}
print_r($translations);
?>
http://codepad.viper-7.com/gCKoI9

<?php
$languageArray = ARRAY();
$my_csv_it = 'hello,ciao goodbye,arrivederci';
$tmp_array_it = explode(' ', $my_csv_it);
foreach ($tmp_array_it AS $text) {
$pairs = explode(',',$text);
$languageArray['it'][$pairs[0]] = $pairs[1];
}
print_r ($languageArray);
?>

Related

Call a single cell from a .CSV using PHP

I've a problem to import a single cell in csv,
i have a csv file that contain 7 column and ~1420 row,
i need to read only the 4 column number in 1420's row, how can i do it?
<?php
$url = "wp-admin/ftp/test.csv";
$csvData = file_get_contents($url);
$lines = explode("\n", $csvData);
$array = array();
foreach ($lines as $line) {
$array[] = str_getcsv($line);
}
echo $array[1];
?>
with this i have an array to output with all cell in one row,
but i need to take the third number in that row, and not all of it.
I believe $array is multidimensional the following should print what you want:
echo $array[1419][3];
Otherwise you can print it to check how it is structured:
print_r($array);
UPDATE: unidimensional
foreach ($lines as $line) {
$array[] = str_getcsv($line)[3];//PHP 5.4
}
echo $array[1419];

multi-dimensional array possibly

I have two files that I need opened, I'm using php file to read them
$lines = file('/home/program/prog_conf.txt');
foreach ($lines as $line) {
$rows = preg_split('/\s+/', $line);
Followed by:
$lines = file('/home/domain/public_html/base/file2.cfg');
foreach ($lines as $line) {
$rows = preg_split('/=/', $line);
As I work with these two files, I need to pull info from the second one, which I seperated by =, however, I'm not sure this is the best thing to do. I wanted to add data checking from the database. The db details are in the second file like so:
dbname = databasename
dbuser = databaseuser
dbpass = databasepassword
If I echo the $rows[2], I get everything all the information I need on a single line, not on seperate lines. Meaning:
databasename databaseuser databasepassword
How do I split the information up so I can use the entries one by one?
How about:
$lines = file('/home/domain/public_html/base/file2.cfg');
$all_parts = array()
foreach ($lines as $line) {
//explode pulls apart a string based on the first value, so you could change that
//to a '=' if need be
array_merge($all_parts,explode(' ', $line));
}
This would get you all the parts of the file, one at a time, into an array. Which is what I think you wanted.
If not, just explode as needed
Maybe this aproach helps:
First as i see your second file has multiple lines, so what would do is something like this:
Assumin that every key as "db" in common we can do something like this.
$file = fopen("/home/domain/public_html/base/file2.cfg", "rb");
$contents = stream_get_contents($handle); // This function return better performance if the file isn't too large.
fclose($file);
// Assuming this is your return from the file
$contents = 'dbname = databasename dbuser = databaseuser dbpass = databasepassword';
$rows = preg_split('/db+/', $contents); // Splinting keys "db"
$result = array();
foreach($rows as $row){
$temp = preg_replace("/\s+/", '', $row); // Removing extract white spaces
$temp = preg_split("/=/", $temp); // Splinting by "="
$result[] = $temp[1]; // Getting the value only
}
var_dump ($result);
I hope this help you can try this code maybe with little modifications but works.

Subtraction between data in file1 and file2 using PHP

Suppose that I have 2 files:
File1.txt
10;30;15;40;12;14;15
23;32;10;50;12;54;60
File2.txt
2;4;5;6;7;8;9
3;6;7;8;9;0;7
I want to subtration between these 2 files. Ex 10 - 2........
PHP code:
$file1 = 'File1.txt';
$file2 = 'File2.txt';
if(file_exists($file1)){
$files = fopen($file1,'r');
while(!feof($files)){
$data = explode(";",fgets($files));
if($title ==""){
$title = $data[0];
}
if(!empty($data[3])){
$cate = $data[3];
$filepmta = fopen($file2,'r');
while(!feof($filepmta)){
$hourData = explode(";",fgets($filepmta));
if(!empty($hourData[3])){
if($title ==""){
$title = $hourData[0];
}
if(!empty($btnHour)){
echo $percentRed = ((int)$data[2] - (int)$hourData[2]);
//it loads page so long time so I don know what's error.
}
}
}
It loads the page is so long time.I don know how to fix this,Anyone know help me please,thanks.
I would recommend just simply opening both files and storing the contents of the file into memory. IE Create 2 simple loops (not nested) which iterates through both files respectively and saves the content to an array.
Then make one more loop after the first two. Iterate through the third loop based on the array size of the first two. (I'm assuming you can assume they are both the same size, but it will be a good idea to add checks to make sure loop 1 and loop 2 produce the same size/length arrays.
Within the 3rd loop iterate through both previously two generated arrays with the same index.
Pseudo Code // even tho I said I'd do pseudo code, I ended up doing it all. :-/
$file_values1 = $file_values2 = $answers = array();
while(!feof($file1)) $file_values1[] = explode(';', fgets($file)); // loop 1
while(!feof($file2)) $file_values2[] = explode(';', fgets($file)); // loop 2
foreach($file_values1 as $key1 => $sub_array) { // loop 3
foreach($sub_array as $key2 => $value) // loop 4; hehe, oh wellz
{
$answers[] = $file_values1[$key1][$key2] = $file_values2[$key1][$key2]
}
}
Basically, the nested loop 4, meh. There ARE faster answers. The 3rd loop can be improved upon, it's O(N^2). I'll leave that for you to optimize. No free lunches. :-)
fgets() doesn't move the file pointer after the last line, so you're staying on the last line, feof() still returns false and you're trapped in an infinite loop.
The common way of doing what you want is:
while (($line = fgets($handle)) !== false) {
echo $line;
}
Have a look at the code example in fgets() documentation, it's quite exhaustive.
You're making this way more complicated than it has to be.
Open your files and read them both in with file(), which will give you an array of lines in each file.
Iterate over both line arrays simultaneously with a MultipleIterator.
Convert each lines' contents to arrays with str_getcsv() and an array_map() trick.
Iterate over each line values with another MultipleIterator.
Compute the subtraction and print it.
That's all it takes! I've implemented the above algorithm below.
$file1 = 'File1.txt';
$file2 = 'File2.txt';
$file1 = file( $file1);
$file2 = file( $file2);
$iter = new MultipleIterator;
$iter->attachIterator( new ArrayIterator( $file1));
$iter->attachIterator( new ArrayIterator( $file2));
foreach( $iter as $element) {
list( $line1, $line2) = array_map( 'str_getcsv', $element, array( ';', ';'));
$val_iter = new MultipleIterator;
$val_iter->attachIterator( new ArrayIterator( $line1));
$val_iter->attachIterator( new ArrayIterator( $line2));
foreach( $val_iter as $value) {
list( $el1, $el2) = $value;
echo ($el1 - $el2); echo ";";
}
echo "\n";
}
You can see from this demo, which statically defines the files as arrays, that this produces:
8;26;10;34;5;6;6;
20;26;3;42;3;54;53;

tab-delimited string to XML with PHP

I'm trying to write the tab-delimited content of a variable to XML like this:
$tsvData = str_getcsv($input, "\t");
foreach($tsvData as $line => $row) {
if($line > 0) {
$xmlWriter->writeElement('NAME', $row[0]);
$xmlWriter->writeElement('CAKE', $row[1]);
$xmlWriter->writeElement('BODYPART', $row[2]);
}
}
But it's only writing one character per XML tag instead of everything between each tab. When I use SplFileObject, geting the same tsv data but from a file, it works. What am I doing wrong with the str_getcsv function?
Thanks
The str_getcsv() function returns a 1-dimensional array, but you're treating it like it's returning a 2-dimensional array.
Edit:
To clarify, str_getcsv() has no concept of "lines". Instead of doing this:
$tsvData = str_getcsv($input, "\t");
Thinking that you'll get an array of lines, each one containing an array of columns, you have to do something like this:
$lines = explode("\n", $input);
$tsvData = array();
foreach ($lines as $line) {
$tsvData[] = str_getcsv($line, "\t");
}
// now $tsvData is a 2-dimensional array of lines/columns like you were wanting

Basic fileread question in PHP /

I have a 12 XML files from which I am extracting ONE CSV file, from which - I am extracting column 1 and appending values to a tt.txt file .
NOW, I need to extract the values from this .txt file... everytime data is written to it ...
But the problem is , when I use
$contents = fread ($fd,filesize ($filename));
fclose ($fd);
$delimiter = ',' ;
$splitcontents = explode($delimiter, $contents);
IT reads ONLY from the first value of the file , every time a tt.txt file is appended !
I hope u understand the problem .. What I need is , I want $contents to have only the new data that was appended... instead it reads from the start of the file everytime...
Is there a way to achieve this, or does php fail ?/
This prob is extraction from TXT file- > performing computations- > writing INTO a new txt file . The problem being that I can't read from a middle value to a new value.. PHP always reads from the start of a file.
I think you need to store the last file position.
Call filesize to get current length, read the file, later, check if filesize is different (or maybe you know this some other way, and use fseek to move the cursor in the file, then read from there.
IE:
$previousLength = 0;
// your loop when you're calling your new read function
$length = filesize($filename);
fseek($fd,$previousLength);
$contents = fread($fd,$length - $previousLength);
$previousLength = $length;
It is only reading the first field because PHP does not automatically assume that a newline character (\n) means a new record; you have to handle this, yourself.
Using what you already have, I would do the following:
$contents = fread($fd, filesize($filename));
close($fd);
/* Now, split up $contents by newline, turning this into an array, where each element
* is, in effect, a new line in the CSV file. */
$contents = explode("\n", $contents);
/* Now, explode each element in the array, into itself. */
foreach ($contents as &$c) {
$c = explode(",", $c);
}
In the future, if you want to go line-by-line, as you run the risk of hogging too many resources by reading the entire file in, use fgets().
I'm not great at arrays but it sounds to me like you need an associative array (I'm doing a similar thing with the following code.
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$parts = explode(',', $line);
if (count($parts) > 0) {
$posts = array();
$posts[] = array('name' => $parts[3],'email' => $parts[4],'phone' => $parts[5],'link' => $parts[6],'month' => $parts[0],'day' => $parts[1],'year' => $parts[2]); }
foreach ($posts as $post):
$post = array_filter(array_map('trim', $post));

Categories