I am trying to read the contents of a file line by line with Laravel.
However, I can't seem to find anything about it anywhere.
Should I use the fopen function or can I do it with the File::get() function?
I've checked the API but there doesn't seem to have a function to read the contents of the file.
You can use simple PHP:
foreach(file('yourfile.txt') as $line) {
// loop with $line for each line of yourfile.txt
}
You can use the following to get the contents:
$content = File::get($filename);
Which will return a Illuminate\Filesystem\FileNotFoundException if it's not found. If you want to fetch something remote you can use:
$content = File::getRemote($url);
Which will return false if not found.
When you have the file you don't need laravel specific methods for handling the data. Now you need to work with the content in php. If you wan't to read the lines you can do it like #kylek described:
foreach($content as $line) {
//use $line
}
You can use
try
{
$contents = File::get($filename);
}
catch (Illuminate\Contracts\Filesystem\FileNotFoundException $exception)
{
die("The file doesn't exist");
}
you can do something like this:
$file = '/home/albert/myfile.txt';//the path of your file
$conn = Storage::disk('my_disk');//configured in the file filesystems.php
$stream = $conn->readStream($file);
while (($line = fgets($stream, 4096)) !== false) {
//$line is the string var of your line from your file
}
You can use
file_get_contents(base_path('app/Http/Controllers/ProductController.php'), true);
$tmpName = $request->file('csv_file');
$csvAsArray = array_map('str_getcsv', file($tmpName));
Related
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 );
?>
I'm trying to make my PHP script open more than 1 text document and to read them.
My current script is as follows:
<?php
//$searchthis = "ignore this";
$matches = array();
$FileW = fopen('result.txt', 'w');
$handle = #fopen("textfile1.txt", "r");
ini_set('memory_limit', '-1');
if ($handle)
{
while (!feof($handle))
{
$buffer = fgets($handle);
if(stripos($buffer, $_POST["search"]) !== FALSE)
$matches[] = $buffer;
}
fwrite($FileW, print_r($matches, TRUE));
fclose($handle);
}
?>
I'm trying to fopen like a bunch of files, maybe like 8 of them or less.
How would I open, and read all these files?
Any help is GREATLY appreciated!
Program defensively, check the return's from functions to ensure you are not making incorrect assumptions about your code.
There is a function in PHP to read the file and buffer it:
enter link description here
I don't know why you would want to open a lot of files, it surely will use a lot of memory, anyway, you could use the file_get_contents function with a foreach:
$files = array("textfile1.txt", "textfile2.txt", "textfile3.txt");
$data = "";
foreach ($files as $file) {
$data .= #file_get_contents($file);
}
echo $data;
There is a function in php called file which reads entire file into an array.
<?php
// "file" function creates array with each line being 1 value to an array
$fileOne = file('fileOne.txt');
$fileTwo = file('fileTwo.txt');
// Print an array or do all array magic with $fileOne and $fileTwo
foreach($fileOne as $fo) {
echo $fo;
}
foreach($fileTwo as $ft) {
$echo $ft;
}
?>
Read more about : file function ion php
I have a little problem with this code I have here. This code searches in a txt file and returnes what it has found.
Now what I want to do is change the file path with a $_GET method
But when I put in a $_GET method inside the "" it just says alot of errors such as "Your path cannot be empty"
What does not work:
$handle = #fopen(."$_GET['filepath']"., "r");
How I want it
$handle = #fopen("I/want/this/$_get/method", "r");
Full code
<?php
function find_value($input) {
// $input is the word being supplied by the user
$handle = #fopen("/users/edwin/list.txt", "r");
if ($handle) {
while (!feof($handle)) {
$entry_array = explode(":",fgets($handle));
if ($entry_array[0] == $input) {
return $entry_array[1];
}
}
fclose($handle);
}
return NULL;
}
?>
Thanks :)
Check the way you're handling your quotes.
$handle = #fopen($_GET['filepath'], "r");
Since it's a variable, it does not have to be encapsulated at all, unlike a string.
How can one retrieve a varibale for instance alias /MyDirectory/ "C:/MyDirectory/MyDirectory/" from http.conf using PHP. Is there an easier way than to open http.conf and read it line by line?
Thanks
You could always use fgets() to read single lines from a file. But why would you want to tinker with your server settings from your program?
$handle = fopen('httpd.conf', 'r');
if($handle) {
while($buffer = fgets($handle) !== false) {
// do something with the data you read
}
if (!feof($handle)) {
echo 'An error occured';
}
fclose($handle);
}
I'm trying to define an array with a list of file urls, and then have each file parsed and if a predefined string is found, for that string to be replaced. For some reason what I have isn't working, I'm not sure what's incorrect:
<?php
$htF = array('/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension', '/home/folder/file.extension');
function update() {
global $htF;
$handle = fopen($htF, "r");
if ($handle) {
$previous_line = $content = '';
while (!feof($handle)) {
$current_line = fgets($handle);
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
{
$output = shell_exec('URL.COM');
if(preg_match('#([0-9]{1,3}\.){3}[0-9]{1,3}#',$output,$matches))
{
$content .= 'PREDEFINED SENTENCE '.$matches[0]."\n";
}
}else{
$content .= $current_line;
}
$previous_line = $current_line;
}
fclose($handle);
$tempFile = tempnam('/tmp','allow_');
$fp = fopen($tempFile, 'w');
fwrite($fp, $content);
fclose($fp);
rename($tempFile,$htF);
chown($htF,'admin');
chmod($htF,'0644');
}
}
array_walk($htF, 'update');
?>
Any help would be massively appreciated!
Do you have permissions to open the file?
Do you have permissions to write to /tmp ?
Do you have permissions to write to the destination file or folder?
Do you have permissions to chown?
Have you checked your regex? Try something like http://regexpal.com/ to see if it's valid.
Try adding error messages or throw Exceptions for all of the fail conditions for these.
there's this line:
if(stripos($previous_line,'PREDEFINED SENTENCE') !== FALSE)
and I think you just want a != in there. Yes?
You're using $htF within the update function as global, which means you're trying to fopen() an array.
$fh = fopen($htF, 'r');
is going to get parsed as
$fh = fopen('Array', 'r');
and return false, unless you happen to have a file named 'Array'.
You've also not specified any parameters for your function, so array_walk cannot pass in the array element it's dealing with at the time.