php reading from file and manipulating the data - php

I am having some difficulty with reading info from a text file. Is it possible to use php and get one line at a time, and compare that line to a variable, one character at a time? Every time I add the character searching algorithm it messes up. or does the file reading only do full files/lines/character
ex:
$file=fopen("text/dialogue.txt","r") or exit("unable to open dialogue file");
if($file == true) {
echo "File is open";
fgets($file);
$c = "";
while(!feof($file)) {
$line = fgets($file)
while($temp = fgetc($line)) {
$c = $c . $temp;
//if statement and comparrison
}
}
} else {
echo "File not open";
}
fclose($file);

You may use php file function to read a file line by line
<?php
$lines = file("myfile.txt");
foreach($lines as $line){
## do whatever you like here
echo($line);
}
?>
Please check php manual
http://php.net/manual/en/function.file.php

Related

Check if value is in an array created from a txt file

I want to check if a value is in array created from a text file (a list of email addresses).
Why neither of these solutions work? (foreach or in_array)
(I've tried printing the array $text and it's ok, no problem coming from file.txt, same thing with $search)
$myfile = fopen("file.txt", "r") or die("Unable to open file!");
while(!feof($myfile)) {
$text[] = fgets($myfile);
}
fclose($myfile);
$search=$_POST['something'];
foreach ($text as $val) {
if (strpos($search, $val) !== FALSE) {
echo "oK";
}
}
/* OR * /
if (in_array($search, $text)) {
echo "OK"; }
Personally, I would not put an entire file input input into an array as its a waste of memory you're already using reading from a file (specially if its large).
You can instead do your "like" condition inside of the loop. I would use str_contains for ease if your PHP version supports it. Build an array based on found results.
if (!isset($_POST['something'])) die('Missing search term');
# TODO: Handle this Exception better
$emails = fopen("file.txt", "r") or die("Unable to open file");
$similarEmails = [];
while(!feof($emails))
if (str_contains(($line = fgets($emails)), $_POST['something']))
$similarEmails[] = $line;
fclose($emails);
References:
str_contains

fgetCsv Returning null values for csv file in php

I have a csv file placed at path
#http://thevowapp.com/brandstore/values.csv
$f = fopen("http://thevowapp.com/brandstore/values.csv", "w+");
if(!f)
{
echo "Error";
}
$line = fgetcsv($f);
echo json_encode($line);
I am trying to parse it, however the fgetCsv keeps on returning null. What could be the error?
Problems:
You try to open a remote file with w+ (write) access. Use r for read.
You check f (undefined constant). Use$f`.
You don't loop fgetcsv, so you won't get more than the header line.
Try:
$f = fopen('http://thevowapp.com/brandstore/values.csv', 'r');
if(!$f) {
echo 'Error';
exit;
}
$out = array();
while ($line = fgetcsv($f)) {
$out[] = $line;
}
echo json_encode($out, JSON_PRETTY_PRINT);
Remove the pretty print option when you're happy.

Can I add an image path from a .txt file in a webpage using PHP?

I need to dynamically add in the img src full file path to a file from a .txt file. So far i have been using the below code to populate titles, and descriptions:
< ?php
$myFile = "film_music/feature1.txt";
$lines = file($myFile);//file in to an array<br />
echo $lines[0]; //line 1
? >
The feature file contains all details for movies that will eventually be displayed here:
http://www.londonosophy.com/film_music2.php
Currently the file contains the following rows:
Sightseers (2012)
Dark comedy, featuring Alice Lowe
images/Sightseers-TinaPencil.jpg
Does anyone know php code that can read line X (or line 3 in this case) and dynamically populate the img src="" file path?
Many thanks in advance for your suggestions!
If you need to iterate over lines and need to check if line contains file path (for example, if sometimes there are white lines between blocks and sometimes they are missing), then:
<?php
$myFile = 'film_music/feature1.txt';
$lines = file($myFile);
$needle = 'images/';
$needleLen = strlen($needle);
foreach ($lines AS $line) {
$line = trim($line);
if (substr($line, 0, $needleLen) == $needle) {
echo '<img src="' . $line . '" alt="" />';
}
}
?>
You need to fetch 3rd line of the file every time, because it contains that path of the image.
<?php
global var $raw;
$myFile = "film_music/feature1.txt";
// open file...
$lines = file($myFile);//file in to an array<br />
for($i=2;$i<=no_of_lines;$i+3){
$raw = $lines[$i];
}
// Populate $raw variable where you need.
?>
Use $fh = fopen(...) and loop every line.
while (!feof($fh)) {
$line = fgets($fh);
if ($line === false) {
throw new Exception("File read error");
}
[do your things.]
}
http://www.php.net/manual/en/function.fopen.php
You can read each line of text line as:
$lines=file('file.txt');
$lines=array();
$fp=fopen('file.txt', 'r');
while (!feof($fp))
{
$line=fgets($fp);
//process line however you like
$line=trim($line);
//add to array
$lines[]=$line;
}
fclose($fp);
if you don't need any special processing, this should do what you're looking for
$lines = file($lines, FILE_IGNORE_NEW_LINES);
may this help you... :)
you can check all line of text file with in_array("you want", $lines) as you desire...if its not dynamically....

Get only one line from a web page

Hi, I have this file test1.php and in the other file test.php I have this
php code running:
<?php
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$line = '0';
if($f = fopen($file, 'r')){
$line = fgets($f); // read until first newline
fclose($f);
}
echo $line;
?>
The idea is to get just the second line of the web page test1.php.
Second Line
I've tried to change the $line = '2'; but no affect, it just displays the first line.
I need Help.
You can use file which reads a file into an array, you can then grab whichever line you want by using the index you want.
For example:
data.txt:
line one
line two
line three
line four
PHP code:
$file = file('data.txt');
echo $file[1]; // echo line number 2, remember arrays start at 0!
Updated PHP code for new versions (5.4):
echo file('data.txt')[1];
This should work. Obviously, change only the value of $linetofetch:
<?php
// Write here the number of the line you want to fetch.
$linetofetch = 2;
$file = "http://inviatapenet.gethost.ro/sop/test1.php";
$currentline = 1;
if($f = fopen($file, 'r')){
while ($currentline <= $linetofetch) {
$line = fgets($f); // read until first newline
$currentline++;
}
fclose($f);
}
echo $line;
?>

How to generically open a file in php

I've looked for questions on this topic, but failed to get what I'm looking for. This is for C++, I need similar for PHP. This is for including php files, I just want to read a CSV file.
I have this:
if(file_exists("data.csv")){
echo "CSV file found";
$csv_data = file_get_contents("data.csv");
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line){
$array[] = str_getcsv($line);
}else {echo "File not found";}
But I want to NOT specify the file name - i.e. generically load/read/open the file.
Is there any simple why of doing that? Doesn't make sense, but I was told to not have anything hard coded in my PHP script.
Thanks in advance.
use fgetcsv
if(file_exists("data.csv")){
echo "CSV file found";
$handle = fopen("data.csv", "r");
if(!$handle) die("Could not open file!");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$row++;
for ($c=0; $c < $num; $c++) {
echo $data[$c] . "<br />\n";
}
}
fclose($handle);
}else {echo "File not found";}
If you may not have anything hard coded in your script, you need to put those hardcoded things into some sort of external config file. You will have to hardcode the name of that config file into your bootstrap or whatever comes first in your application. Once the config is loaded, make the configuration data available in the places where it is needed. Not hardcoding configuration data into your code will allow you to create more reusable components and code, e.g. CSV Reader that can read any CSV file instead of a CSV Reader that can only read that one particular CSV file hardcoded into it.
Example:
// config.php
<?php
return array(
'csvFile' => '/path/to/file.csv',
…
);
// bootstrap.php
<?php
$config = include '/path/to/config.php';
…
// someFile.php
<?php
include '/path/to/bootstrap.php';
$file = new SplFileObject($config['csvFile']);
$file->setFlags(SplFileObject::READ_CSV);
foreach ($file as $row) {
// Do something with values
}
Put your code into a function...
function open_file($file_name)
{
if (!file_exists($file_name))
{
return false;
}
$csv_data = file_get_contents($file_name);
$lines = explode("\n", trim($csv_data));
$array = array();
foreach ($lines as $line)
{
$array[] = str_getcsv($line);
}
return $array;
}

Categories