PHP read command output and process in array - php

I have following working code which read file contain and put into array but now i want to run command and place its output in array for example ls command
<?php
$path = "file.txt";
$file = fopen($path, 'r');
$data = fread($file, filesize($path));
fclose($file);
$lines = explode(" ",$data);
echo "<p><h1>$lines[0]</h1></p>";
?>
How do i read command output and place in array?

You can use shell_exec:
<pre><?php
$output = shell_exec('ls');
print_r($output);

My Preferred method would be to use popen. I would be trivial to put the results in an array
$fp = popen ("ls -l", "r");
$array = array();
while ($rec = fgets($fp)){
$array[] = trim($rec);
}
// do something cool with array

Related

PHP Replace all values in the third column in a csv file

I am trying to replace some hyperlinks in a csv file, like this one:
[https://assets.suredone.com/683987/media-pics/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. Here is my code:][1]. Here is my code:
<?php
$in_file = 'gabriel-images-urls.csv';
$out_file = 'results.csv';
$fd = fopen($in_file, "r");
$new_array= array();
$toBoot= array();
while ($data = fgetcsv($fd)) {
echo '<pre>';
if (strpos($data[2],'media-pics') !== false) {
$data[2]=str_replace('media-pics','media-photos',$data[2]);
fputcsv($fd, $data);
// echo $output;
}
}
?>
The new link for example must look like this:[1]https://assets.suredone.com/683987/media-photos/6164307j-gabriel-61643-proguard-steel-shock-absorber-for-select-chevrolet-gmc-models.jpg. The goal is he "media-pics" substring to be replaced with "media-photos". At this point nothing happens in the file. I think this is because the file is open only for reading but I am not sure.
Can you not simply do a string replacement on the whole file rather than attempting to load and process each line of the file using fgetcsv?
<?php
$srcfile='gabriel-images-urls.csv';
$outfile='results.csv';
$csvdata=file_get_contents( $srcfile );
$moddata=str_replace('media-pics','media-photos',$csvdata);
file_put_contents( $outfile, $moddata );
?>

how can I sort a text file in php

english, lang1, lang2
rat, rat_lang1, rat_lang2
ball, ball_lang1, ball_lang2
air, air_lang1, air_lang2
If I have this text file I read in php, how can I sort it starting the second line, the first line being the heading of the file. So that the file will print out like..
english....
air....
ball...
rat....
I read the file using fopen, put it in $content using fread, used explode with new line. I can see the array of lines but cannot figure out how to sort it. Any suggestions would be appreciated.
Much of this solution was answered within the comments in response to your question. All put together you're looking for something like:
<?php
$f = file("text.txt"); //read the text file into an array
$newf = fopen("newtext.txt", "w+"); //open another file
$header = $f[0]; //store the first element of the array as $header
echo $header."<br>"; //and echo the header
fwrite($newf, $header); //write the header to the new file
array_shift($f); //then remove the first element of the array i.e. the header
sort($f); //sort the array (no flag param = alphabetical sort)
foreach($f as $line){ //loop through the sorted array
echo $line."<br>"; //print each element as it's own line
fwrite($newf, trim($line)."\n"); //write other elements to new file on own line
}
fclose($newf); //close the file
?>
Try this:
$data = trim(file_get_contents('sort_test.txt'));
$data = explode("\n", $data);
$array_order = array();
$fileLocation = getenv("DOCUMENT_ROOT") . "/myfile.txt";
$file = fopen($fileLocation, "w");
for ($i = 0; $i < count($data); $i++) {
($i > 0) ? $array_order[$i] = $data[$i] : fwrite($file, $data[0]);
}
sort($array_order);
$data = implode("\n", $array_order);
fwrite($file, $data);
fclose($file);
echo 'file created - location::' . $fileLocation;
Output myfile.txt
english, lang1, lang2
air, air_lang1, air_lang2
ball, ball_lang1, ball_lang2
rat, rat_lang1, rat_lang2
Maybe the new file (myfile.txt) will needs write permission to the directory you are writing to , in my case the file has been stored into C:/.../htdocs/myfile.txt

How to replace one line in php?

I have test.txt file, like this,
AA=1
BB=2
CC=3
Now I wanna find "BB=" and replace it as BB=5, like this,
AA=1
BB=5
CC=3
How do I do this?
Thanks.
<?php
$file = "data.txt";
$fp = fopen($file, "r");
while(!feof($fp)) {
$data = fgets($fp, 1024);
// You have the data in $data, you can write replace logic
Replace Logic function
$data will store the final value
// Write back the data to the same file
$Handle = fopen($File, 'w');
fwrite($Handle, $data);
echo "$data <br>";
}
fclose($fp);
?>
The above peace of code will give you data from the file and helps you to write the data back to the file.
Assuming that your file is structured like an INI file (i.e. key=value), you could use parse_ini_file and do something like this:
<?php
$filename = 'file.txt';
// Parse the file assuming it's structured as an INI file.
// http://php.net/manual/en/function.parse-ini-file.php
$data = parse_ini_file($filename);
// Array of values to replace.
$replace_with = array(
'BB' => 5
);
// Open the file for writing.
$fh = fopen($filename, 'w');
// Loop through the data.
foreach ( $data as $key => $value )
{
// If a value exists that should replace the current one, use it.
if ( ! empty($replace_with[$key]) )
$value = $replace_with[$key];
// Write to the file.
fwrite($fh, "{$key}={$value}" . PHP_EOL);
}
// Close the file handle.
fclose($fh);
The simplest way (if you are talking about a small file as above), would be something like:
// Read the file in as an array of lines
$fileData = file('test.txt');
$newArray = array();
foreach($fileData as $line) {
// find the line that starts with BB= and change it to BB=5
if (substr($line, 0, 3) == 'BB=')) {
$line = 'BB=5';
}
$newArray[] = $line;
}
// Overwrite test.txt
$fp = fopen('test.txt', 'w');
fwrite($fp, implode("\n",$newArray));
fclose($fp);
(something like that)
You can use Pear package for find & replace text in a file .
For more information read
http://www.codediesel.com/php/search-replace-in-files-using-php/

mysql foreach fwrite

I use some code here, transfer mysql query data into json data and write into a file. where is the problem? why the file is zero kb?
while($row = mysql_fetch_array($Query)){
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
$countfile="data.txt";
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
$fp = fopen($countfile, 'r');
fwrite($fp, $jsondata);
fclose($fp);
}
Several things.
You dont need (and should avoid) to open the file in every iteration
You open the file read-only (r)
At all something like this should do it
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata = json_encode($arr);
fwrite($fp, $jsondata);
}
fclose($fp);
Additional you append separate json structures into the file, what is probably not, what you want. You should first collect all you want to store into one json structure and save it then
$data = array();
while($row = mysql_fetch_array($Query))
{
$data[] = array ('name'=>$row['name']);
}
file_put_contents('data.txt', json_encode($data));
This feels more like what you are probably looking for.
Because you're reopening the file as read only
$fp = fopen($countfile, 'r');
try
$fp = fopen($countfile, 'w'); // to write
or
$fp = fopen($countfile, 'a'); // to append
you could also open the file for writing at the start, append your rows in a variable and then write it all together to the file.
$countfile="data.txt";
$fp = fopen($countfile, 'w');
while($row = mysql_fetch_array($Query))
{
$arr = array ('name'=>$row['name']);
$jsondata .= json_encode($arr) . "\n";
}
fwrite($fp, $jsondata);
fclose($fp);
You are opening the file read-only. You probably want 'w' or 'r+'.
You are opening the file for reading only
$fp = fopen($countfile, 'r');
You also dont need
if(!file_exists($countfile))
{
fopen($countfile,"w");
}
just use:
$fp = fopen($countfile, 'w');

Find and edit text files via PHP

Let say a text file contain
Hello everyone, My name is Alice, i stay in Canada.
How do i use php to find "Alice" and replace it with "John".
$filename = "C:\intro.txt";
$fp = fopen($filename, 'w');
//fwrite($fp, $string);
fclose($fp);
$contents = file_get_contents($filename);
$new_contents = str_replace('Alice', 'John', $contents);
file_put_contents($filename, $new_contents);
Read the file into memory using fread(). Use str_replace() and write it back.
If its a big file, use iteration instead of reading all into memory
$f = fopen("file","r");
if($f){
while( !feof($f) ){
$line = fgets($f,4096);
if ( (stripos($line,"Alice")!==FALSE) ){
$line=preg_replace("/Alice/","John",$line);
}
print $line;
}
fclose($f);
}

Categories