I have a script that looks through a file and returns every newline as an array element.
$file = fopen("dict.txt", "r");
$entries = array();
while (!feof($file)) { $entries[] = fgets($file); }
fclose($file);
I also have a script which does some utilities with a $_GET variable.
$word = htmlspecialchars($_GET["user"]);
$letters = $word[0] . $word[1] . $word[2];
What I would like to do now is to echo all elements in the $entries array beginning with $letters.
Any help would be much appreciated.
try
foreach($entries as $entry) {
if (strpos($entry, $letters) === 0) {
echo $entry;
}
}
Related
I have a file that looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]||55.183.567
I made a function that when executed adds a given number or removes it if already present, which is $added and equals 100 for this example. This is my code:
$added = $_GET['added']; //100 for this example
$f = fopen($file, "w");
$list = file($file);
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
foreach ($details as $key => $value) {
if ($key == 5) {
$newline .= str_replace("[" . $added . "]", "", $value);
} else {
$newline .= $value . "||";
}
}
$line = $newline . "\n";
}
fputs($f, $line);
}
fclose($f);
}
this code is supposed to remove the [100] from the Rocky line since its already present which it kinda does. However, upon further execution instead of adding it back it duplicates the Rocky line and messes it up so the file looks like this:
1||Allan||34||male||USA||||55.789.980
2||Georg||32||male||USA||||55.756.180
3||Rocky||21||male||USA||[100][200]55.183.567
3||Rocky||21||male||USA||[100][200]55.183.567
||
||
why is it doing this? I cant make any sense out of it...
Thank you.
First, you should read the file before you open it for output, because opening with the w mode truncates the file.
Second, you don't need to loop over the fields in $details if you just want to change one of them. Just access and assign it by index.
Then you can put the line back together with implode().
$list = file($file);
$f = fopen($file, "w");
foreach ($list as $line) {
$details = explode("||", $line);
if (preg_match("~\b$details[0]\b~", 3)) {
if (strpos("[$added]", $details[5]) === false) {
$details[5] = "[$added]" . $details[5];
} else {
$details[5] = str_replace("[$added]", "", $details[5]);
}
$line = implode('||', $details)
}
fputs($f, $line);
}
fclose($f);
I have two columns in my csv file: first_column and second_column. I would like to group all the rows in second column into one string separated by "," if they all have the same word in the first column then output them into a text file.
first_column second_column
a Chris
a Jake
a Paula
b Anita
b Lionel
b Sheila
Desired output
a: Chris, Jake, Paula
b: Anita, Lionel, Sheila
This is what I tried. I seem to be only getting the first letter from the second_column. Any pointers would be great.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");
$data = array();
if ($csv_file)
{
while (($line = fgets($csv_file)) !== false)
{
$column_1 = $line[0];
$column_2 = $line[1];
if (!empty($column_1))
{
$data [$column_1] = column_2;
}
}
fclose($csv_file);
fclose($text_file);
}
else
{
// error opening the file.
}
//print_r($data);
This should work for you:
Here I first get your .csv file into an array with file(). Then I loop through each line and create an array, where the first column is the key and the second column a value of the sub array.
After this you can loop through your created array and implode() each sub array with the key to the expected line which you want. Then you can just save the data with file_put_contents() into your .txt file.
<?php
$csv_file = "test.csv";
$text_file = "test.txt";
$lines = file($csv_file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
array_shift($lines);
foreach($lines as $line) {
list($key, $value) = explode(",", $line); //Change your .csv delimiter here, if you use something else than ,
$data[$key][] = $value;
}
foreach($data as $key => $arr)
$content[] = $key . ": " . implode(",", $arr) . PHP_EOL;
file_put_contents($text_file, $content);
?>
Storing result in an data array and then wring it bacj to text file should work.
$csv_file = fopen("test.csv", "r");
$text_file = fopen("test.txt","w");
$data = array();
if ($csv_file)
{
while (($line = fgets($csv_file)) !== false)
{
$column_1 = $line[0];
$column_2 = $line[1];
if (!isset($data[$column_1]))
{
$data[$column_1] = column_2
} else {
$data[$column_1] = $data[$column_1] .',' . $column_2
}
}
foreach($data as $k=>$d ){
fputs($text_file, "$k: $d") ;
}
fclose($csv_file);
fclose($text_file);
}
else
{
// error opening the file.
}
I have a text file here which I need to be able to convert into rows to extract the second, third, fourth, and fifth values from.
The first 7 values of each row are tab delimited, then there is a newline, then the final three values are tab delimited.
I removed the interrupting newlines so that each row is fully tab delimited.
<?php
$file="140724.txt";
$fopen = fopen($file, "r");
$fread = fread($fopen,filesize("$file"));
fclose($fopen);
$remove = "\n";
split = explode($remove, $fread);
foreach ($split as $string)
{
echo "$string<br><br>";
}
?>
Which produces this.
I'm not sure where to progress from this point. I'm teaching myself PHP and am still quite new to it, so I don't even know if where I've started from is a good place. My instinct is to write the previous output to a new textfile, then create another block of code similar to the first but exploding based on tabs, this time.
Help?
You can process this file in one go like this:
<?php
$file="140724.txt";
$fopen = fopen($file, 'r');
$fread = fread($fopen,filesize($file));
fclose($fopen);
$remove = "\n";
$split = explode($remove, $fread);
$array[] = null;
$tab = "\t";
foreach ($split as $string)
{
$row = explode($tab, $string);
array_push($array,$row);
}
echo "<pre>";
print_r($array);
echo "</pre>";
?>
The result will be a jagged array:
You will need to clean up the 1st and the last element.
That is structured data, delimited by tabs. You can use fgetcsv() to read that data into an array. For an example see the PHP documentation.
<?php
$myfile = fopen("test.txt", "r") or die("Unable to open file!");
// Output one line until end-of-file
while(!feof($myfile)) {
$text[] = fgets($myfile);
}
fclose($myfile);
print_r($text);
?>
There is another answer here which converts file/raw strings into an associative array. It is really very handy in such cases.
function tab_to_array($src='', $delimiter=',', $is_file = true)
{
if($is_file && (!file_exists($src) || !is_readable($src)))
return FALSE;
$header = NULL;
$data = array();
if($is_file){
if (($handle = fopen($src, 'r')) !== FALSE)
{
while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE)
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
fclose($handle);
}
}
else{
$strArr = explode("\n",$src);
foreach($strArr as $dataRow){
if($row = explode($delimiter,$dataRow))
{
if(!$header)
$header = $row;
else
$data[] = array_combine($header, $row);
}
}
}
return $data;
}
/**
* Example for file
*/
print_r(tab_to_array('example.csv'));
/**
* Example for raw string
*/
$str = "name number
Lorem 11
ipsum 22";
print_r(tab_to_array($str, "\t", false));
I have a .txt file that has the following details:
ID^NAME^DESCRIPTION^IMAGES
123^test^Some text goes here^image_1.jpg,image_2.jpg
133^hello^some other test^image_3456.jpg,image_89.jpg
What I'd like to do, is parse this ad get the values into a more readable format, possibly into an array if possible.
Thanks
You can do that easily this way
$txt_file = file_get_contents('path/to/file.txt');
$rows = explode("\n", $txt_file);
array_shift($rows);
foreach($rows as $row => $data)
{
//get row data
$row_data = explode('^', $data);
$info[$row]['id'] = $row_data[0];
$info[$row]['name'] = $row_data[1];
$info[$row]['description'] = $row_data[2];
$info[$row]['images'] = $row_data[3];
//display data
echo 'Row ' . $row . ' ID: ' . $info[$row]['id'] . '<br />';
echo 'Row ' . $row . ' NAME: ' . $info[$row]['name'] . '<br />';
echo 'Row ' . $row . ' DESCRIPTION: ' . $info[$row]['description'] . '<br />';
echo 'Row ' . $row . ' IMAGES:<br />';
//display images
$row_images = explode(',', $info[$row]['images']);
foreach($row_images as $row_image)
{
echo ' - ' . $row_image . '<br />';
}
echo '<br />';
}
First you open the text file using the function file_get_contents() and then you cut the string on the newline characters using the function explode(). This way you will obtain an array with all rows seperated. Then with the function array_shift() you can remove the first row, as it is the header.
After obtaining the rows, you can loop through the array and put all information in a new array called $info. You will then be able to obtain information per row, starting at row zero. So for example $info[0]['description'] would be Some text goes here.
If you want to put the images in an array too, you could use explode() too. Just use this for the first row: $first_row_images = explode(',', $info[0]['images']);
Use explode() or fgetcsv():
$values = explode('^', $string);
Or, if you want something nicer:
$data = array();
$firstLine = true;
foreach(explode("\n", $string) as $line) {
if($firstLine) { $firstLine = false; continue; } // skip first line
$row = explode('^', $line);
$data[] = array(
'id' => (int)$row[0],
'name' => $row[1],
'description' => $row[2],
'images' => explode(',', $row[3])
);
}
By far the best and simplest example of this I have come accross is quite simply the file() method.
$array = file("myfile");
foreach($array as $line)
{
echo $line;
}
This will display all the lines in the file, this is also applicable for a remote URL.
Simple and clear.
REF : IBM PHP Parse
I would like to contribute a file that provides atomic data structures.
$lines = file('some.txt');
$keys = explode('^', array_shift($lines));
$results = array_map(
function($x) use ($keys){
return array_combine($keys, explode('^', trim($x)));
},
$lines
);
Try fgetcsv() with ^ as the separator character:
$file = fopen($txt_file,"r");
print_r(fgetcsv($file, '^'));
fclose($file);
http://www.w3schools.com/php/func_filesystem_fgetcsv.asp
<?php
$row = 1;
if (($handle = fopen("test.txt", "r")) !== FALSE) {
while (($data = fgetcsv($handle, 1000, "^")) !== FALSE) {
$num = count($data);
echo "<p> $num fields in line $row: <br /></p>\n";
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}
?>
Ok, didn't see the edited version, so here's a redo. It's most likely a CSV file that uses carets as the separator, so...
$fh = fopen('yourfile.txt');
$headers = fgetcsv($fh, 0, '^');
$details = array();
while($line = fgetcsv($fh, 0, '^')) {
$details[] = $line;
}
fclose($fh);
youse a list, and split the "image_1.jpg,image_2.jpg" after you explode the string:
list($number, $status, $text, $images) = explode("^", $data);
$splited_images= preg_split(',', $images);
My solution
function parseTextFile($file){
if( !$file = file_get_contents($file))
throw new Exception('No file was found!!');
$data = [];
$firstLine = true;
foreach(explode("\n", $file) as $line) {
if($firstLine) {
$keys=explode('^', $line);
$firstLine = false;
continue;
} // skip first line
$texts = explode('^', $line);
$data[] = array_combine($keys,$texts);
}
return $data;
}
I'm a bit lost for I'm "green" in PHP.
Please, may you teach me how to fix this:
on 'POST' --> Replace a specified array key from a file:
(WRONG:)
<?php
$newData = $_POST["sendData"];
if(isset($_POST['sendData'])){
$file = fopen('fileToOpen.php', 'a');
foreach($file as $key => $val)
{
$data[$key] = explode("|", $val);
}
for($k = 0; $k < sizeof($file); $k++)
{
unset($data[$k][3]);
}
$data[$k][3] = "$newData";
fwrite($file, $data[$k][3]);
fclose ($file);
}
?>
That's wrong as it continues to write:
data1|data2|data3|oldDatanewData
instead of rewrite:
data1|data2|data3|newData
Is there any other technique to achieve something similar? Perhaps with file_put_contents? Am I missing implode?
Thanks!
Dunno what are you asking for but perhaps you only need to serialize and unserialize the array.
$data_array = unserialize(file_get_contents('fileToOpen.php'));
$data_array[$key_you_want_to_change] = $new_data;
file_put_contents('fileToOpen.php', serialize($data_array));
$newData = $_POST['sendData'];
if(isset($_POST['sendData'])){
$file = "fileToOpen.php";
$oldData = file_get_contents($file);
$oldData = eregi_replace("\n","",$oldData);
$FullDataArray = explode("?",$oldData);
$oldDataArray = explode("|",$FullDataArray[1]);
$oldDataArray[3] = $newData;
$newDataString .= "
foreach($oldDataArray as $key=>$val) {
$newDataString .= $val;
if($key!="3") {
$newDataString .= "|";
}
}
$fh = fopen($file, 'w');
fwrite($fh,$newDataString);
fclose($fh);
}
?>