I have a question. How can i get a string from a entry in a textfile.
The texfile looks like:
Blabla2|123456
Blablablabla4|475387638
Blab1|387549900
Now i want to get from Blablablabla4 the number behind the |
Whats the read file function for it?
You can create a custom function, if you need that value often with different keys.
function getValueFromFile($file, $key){
if (($handle = fopen($file, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "|")) !== FALSE) {
if($data[0] == $key){
fclose($handle);
return $data[1];
}
}
fclose($handle);
}
return false;
}
and simply call it like:
echo getValueFromFile("your file name", "Blablablabla4");
Load each line of file to $line and then use function explode('|', $line_variable) for separating a string from int.
$handle = fopen("inputfile.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$line = explode('|', $line);
$string = $line[0];
}
fclose($handle);
} else {
// error opening the file.
}
Related
I have data as below in a CSV file. The green lines are what I'd like to keep.
Basically if someone has a single line, I want to keep it.
If they have multiple lines, I want to remove any where the 3rd column is A - Fully Fit.
After running through the whole file, I then want to save it over the original.
I tried writing the code but not sure if it's a Friday but the logic is escaping me at the moment.
There could be just a single line or there could be dozens. So if an ID has 1000 rows, I would just want to delete the rows for that ID where the 4th column is "A - Fully Fit"
UPDATE
This code works but not sure if it's the most optimal
// DECLARE ARRAYS
$a = Array();
$b = Array();
$c = Array();
// LOOP THROUGH FILE AND COLLECT DUPLICATES
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
$a[$line[1]][] = 'SHAKKA';
}
foreach ($a as $k=>$v) {
if (count($v)>1) {
$b[] = $k;
}
}
}
// IF A DUPLICATE THEN REMOVE ROWS THAT ARE 'A - Fully Fit'
if (($handle = fopen($filename, "r")) !== FALSE) {
while (($golly = fgetcsv($handle, 4096, ",")) !== FALSE) {
if (in_array($golly[1],$b) && $golly[3] == 'A - Fully Fit') {
}
else {
$c[] = $golly;
}
}
}
fclose($handle);
// WRITE THE FILE
$fp = fopen($filename, 'wa+');
foreach ($c as $fields) {
fputcsv($fp, $fields);
}
fclose($fp);
<?php
if (($handle = fopen($filename, "r")) !== FALSE) {
$new_rows = [];
$hash_ids = [];
while (($line = fgetcsv($handle, 4096, ",")) !== FALSE) {
if($line[3] === 'A - Fully Fit'){
if(isset($hash_ids[$line[1]])) continue;
$hash_ids[$line[1]] = true;
}
$new_rows[] = $line;
}
fclose($handle);
// WRITE TO THE FILE
$fp = fopen($filename, 'wa+');
foreach ($new_rows as $current_row) {
fputcsv($fp,$current_row);
}
fclose($fp);
}
In the above code, we maintain a hash(associative array) for each ID. If we have already come across with an ID with A - Fully Fit, then we skip the row, else we add it to the list.
I am getting data from a csv as an array using the fgetcsv function. I want to convert the array into a string, so I have used the implode function.
CODE:
if (($handle = fopen("storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
I am getting the result string say as Ter Aar, Netherlands,4.7159509,52.164688,,211316. But I would like each entry to be enclosed by double quotes. How can I do that?
Expected result: `"Ter Aar", "Netherlands","4.7159509","52.164688","","211316"
My approach #1 -
I passed the " as enclosure following the documentation but it is not working.
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
$datafinal = implode(",",$data);
echo $datafinal;
}
fclose($handle);
}
My approach #2 -
function convert( $str ) {
return '"'.$str.'"';
}
if (($handle = fopen("../storelocations.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",", '"')) !== FALSE) {
//$datafinal = array_map( convert, $data );
$datafinal = implode(",",$data);
echo $datafinal;
//var_dump($data);
}
fclose($handle);
}
This returns a string as "Ter Aar", "Netherlands","4.7159509","52.164688","","""211316".
As you can see the item following the blank data gets three quotes in the beginning.
You can do it as follows
// PHP 5.3 and later
echo $datafinal = implode(",",array_filter($data, function($value) { return $value !== ''; }));
This will help you sure
Thanks
Hope! It will help you
Try following code to read csv file and get data as multi-dimentional array
$csv_data = array_map('str_getcsv', file('../storelocations.csv'));
foreach ($csv_data as $key => $value)
{
var_dump($value); // print each row of csv
var_dump($value[0]) // print first column of each row
}
I am trying to fetch a specific column from a file by using PHP. but so far I got all of it, have no idea how to do this, I can not find any information online so if anyone could help me about this , I will be very appreciated. The data in file is like blow:
20110101,1110.0
20110102,1100.0
20110103,50.0
20110104,6355.0
........
I just want to fetch the second column, here is my PHP code:
$file_handle = fopen("file_name", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
echo $line."<br/>";
}
fclose($file_handle);
Have you tried this (which actually does what you want, without refactoring) :
$file_handle = fopen("file_name", "r");
while (!feof($file_handle)) {
$line = fgets($file_handle);
$cols = explode(',', $line);
echo $cols[1]."<br/>";
}
fclose($file_handle);
??
As Vlad says, use fgetcsv.
// adapted from PHP example
$max_row_len = 1000;
if (($file_handle = fopen("file_name", "r")) !== FALSE) {
while (($data = fgetcsv($file_handle, $max_row_len, ",")) !== FALSE) {
echo $data[1]."<br/>";
}
fclose($file_handle);
}
I've searched the web and looked through existing answers but cant find a solution to this one. I want to use php to do the following task. Here are my files:
csv file 1: member.csv
member1|john|smith|2009
member2|adam|jones|2007
member3|susie|rose|2002
csv file 2: classes.csv
member1|massage|swimming|weights
member2|gym|track|pilates
member3|yoga|running|stretches
I want to output a third file called file3.csv which merges the two above files together based on the key field which is the member number. the output should be like this:
member1|john|smith|2009|massage|swimming|weights
member2|adam|jones|2007|gym|track|pilates
member3|susie|rose|2002|yoga|running|stretches
the delimiter is a bar character. I want to do this just using php - no other languages.
I would be very greatful for a solution.
Matt
Read both files and store data to the array with keys: member1, ...
Write a new file lines in loop:
foreach ($firstArray as $key => $value1) {
$value2 = $secondArray[$key];
// ...
}
<?php
$data = array();
if (($handle = fopen('file1.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = $line;
}
fclose($handle);
}
if (($handle = fopen('file2.csv', 'r')) !== FALSE) {
while (($line = fgetcsv($handle, 0, '|')) !== FALSE) {
$memberId = $line[0];
unset($line[0]);
$data[$memberId] = array_merge($data[$memberId], $line);
}
fclose($handle);
}
ksort($data); // not needed, but puts records in order by member
if (($handle = fopen('file3.csv', 'w')) !== FALSE) {
foreach($data as $key => $value) {
fwrite($handle, "$key|" . implode('|', $value) . "\n");
}
fclose($handle);
}
Try this. It is untested.
$arr_one = array();
if (($fp = fopen("member.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_one[$data[0]] = $data;
}
fclose($fp);
}
$arr_two = array();
if (($fp = fopen("classes.csv", "r")) !== FALSE) {
while (($data = fgetcsv($fp, 1000, ",")) !== FALSE) {
$arr_two[$data[0]] = $data;
}
fclose($fp);
}
$classes_field_count = sizeof(current($arr_two));
$members = array_keys($arr_one);
foreach ($members as $key) {
if (!isset($arr_two[$key])) {
$arr_two[$key] = range(0, ($classes_field_count - 1));
}
unset($arr_two[$key][0]);
$result_arr[$key] = array_merge($arr_one[$key], $arr_two[$key]);
}
if (($fp = fopen("file3.csv", "w")) !== FALSE) {
foreach ($result_arr as $fields) {
fputcsv($fp, $fields, '|');
}
fclose($fp);
}
I need to add columns to an existing csv file ,but i can't find any solution to the problem.I have used "\t" and chr(9) to create columns but no success so please help me by providing me the right solution if any one can
Try this, and have a look at fgetcsv() and fputcsv() in the manual
<?php
$newCsvData = array();
if (($handle = fopen("test.csv", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$data[] = 'New Column';
$newCsvData[] = $data;
}
fclose($handle);
}
$handle = fopen('test.csv', 'w');
foreach ($newCsvData as $line) {
fputcsv($handle, $line);
}
fclose($handle);
?>
Could you try using \r\n instead of \n ?