Getting PHP variables from .txt file and discarding characters - php

I know the pure basics of PHP, and I need help converting text into variables from a .txt file.
The text inside the .txt file (lets call it 'info.txt') is in a single line as follows:
Robert | 21 | male | japanesse |
So what I need is to convert the information in variables as follows:
<?php
$name = 'Robert';
$age = '21';
$sex = 'male';
$nacionality = 'japanesse';
?>
Note that I want to discard the '|' between every data.
How could I do that using PHP? Using arrays? How?

<?php
$file_content = file_get_contents($fileName);
list($name, $age, $sex, $nationality) = explode("|", $file_content);
echo "Hello ". $name;
Use explode to get information in an array.

You can use php's file_get_contents() & explode() functions
$data = file_get_contents('info.txt');
$parsedData = explode("|", $data);
var_dump($parsedData);

You can "explode" a string in PHP using the explode function. You can also use file_get_contents to get the contents of a file. Assuming that the format of the file is always consistent, you can couple explode with list to assign directly to your variables.
For example
<?php
$string = file_get_contents("file.txt");
$lines = explode("\n", $string);
list($name, $age, $sex, $nationality) = explode("|", $lines[0]);
This reads the contents of "file.txt" into an array, and then assigns the first line's contents to the variables $name, $age, $sex, $nationality

Code
//Step 1
$content = file_get_contents('info.txt');
//Step 2
$info = explode('|', $content);
//Step 3
$name = $info[0];
$age = $info[1];
$sex = $info[2];
$nationality = $info[3];
Explaination
First load the contents in info.txt in a variable using the
file_get_contents() function:
$content = file_get_contents('info.txt');
Second, break up the content into little pieces based on the | character using the explode() function. The broken bits will be stored in an array.
$info = explode('|', $content);
Now assign each value in the array from step 2 to a variable
$name = $info[0];
$age = $info[1];
$sex = $info[2];
$nationality = $info[3];
you can do this step in a shorter way using the list() function as shown in the other answers!
Ultra short, one line code for fun
list($name, $age, $sex, $nationality) = explode("|", file_get_contents("file.txt"));

Related

comma separated if value in array is empty

I am stuck with a problem, I have fetched some values from a MySQL query and put them in to an array like so:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = rtrim(implode(',', $fullAddress), ',');
echo $string;
so that I can echo out a users address. The problem I am getting is that even if one of these values does not exist (and some don't because they are not all required fields), the comma is still echoed to the screen like:
add1,, town, br2 5lp
because there is an empty value in the database.
What I want to achieve is something like:
add1, town, br2 5lp
if the second part of the address is missing.
Can anyone help me figure this out?
try this.
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = implode(',', array_filter($fullAddress, 'strlen'));
echo $string;
The problem I am getting is that even if one of these values does not
exist (and some dont because they are not all required fields),
the comma is still echoed to the screen
That is what the implode function in php is supposed to do. If you want a different behavior, you will have to either change the way you create your CSV string or do some extra processing on the information you obtain from the implode function.
So use a for loop or a foreach loop to go through the address array. A for loop is faster than a foreach loop.
Using Foreach:
$add1 = $location->address1;
$add2 = $location->address2;
$twn = $location->town;
$pcode = $location->postcode;
$latitude = $location->lat;
$longitude = $location->lng;
$fullAddress = [$add1, $add2, $twn, $pcode];
$string = "";
foreach($fullAddress as $value)
{
if(!empty($value))
$string .= $value.", ";
}
$string = rtrim($string, ", ");
echo $string;
You can do some extra processing on the created csv string of your own solution by maybe doing a str_replace() of all occurances of ,, with ,. This could be dangerous because if any of the values in your $fullAddress array contain a ,, as a valid string then that will also be replaced too with ,.
What you need is to assure array $fullAddress have no empty value, so php built-in function array_filter make this purpose very easy.
Just change your last codes to:
$string = implode(',', array_filter($fullAddress));
echo $string;
If the second parameter of array_filter is not supplied, all entries of array equal to FALSE will be removed. So just simply use array_filter($fullAddress) it make the code more clear and simple.

Create report in txt file with php

This script for write to a file from php :
<?php
$File = "YourFile.txt";
$Handle = fopen($File, 'a');
$Data = "Jane Doe\n";
fwrite($Handle, $Data);
$Data = "Bilbo Jones\n";
fwrite($Handle, $Data);
print "Data Added";
fclose($Handle);
?>
How to configure align the text like in fpdf (example : $pdf->Cell(20,10,'Title',1,1,'C');) ?
Use str_pad to get a decent result. Say you have 2 rows of data. Like:
Firstname, Lastname
If you want to sort these in a txt file to look nice you can do:
$firstname = "Jane";
$lastname = "Doe";
$firstname = str_pad($firstname, 30); //Force string to be 30 characters length
str_pad will add an amount of spaces to your string untill it reaches the length you want it to. Having all First names at exactly 30 characters will make the Last names appear perfectly sorted behind them as if you're having 2 lists in your TXT file.
Ofcourse if you ever want to read out the file you probebly want to trim away all those unnessary spaces. You can do this with:
$firstname = preg_replace('/\s+/', ' ', $firstname);

PHP How to parse a string and conver to variables

Using PHP, I am looking to parse a string and convert it into variables. Specifically, the string will be a file name, and I'm looking to break the file name into variables. Files are nature photos, and have a uniform format:
species_name-date-locationcode-city
All files names have this exact format, and the "-" is the delimiter. (I can make it whatever if necessary)
an example of the file name is common_daisy-20130731-ABCD-Dallas
I want to break it up into variables for $speciesname, $date, $locationcode, $city.
Any idea on how this can be done? I have seen functions for parsing strings, but they usually take the form of having the name of the variable in the string, (For example "species=daisy&date=20130731&location=ABCD&city=Dallas") which I don't have, and cannot make my file names match that. If I wanted to use a string replace to change the delimiters to variables= I would have to use 4 different delimiters in the filename and that wont work for me.
Thanks for anyone who tries to help me with this issue.
list($speciesname, $date, $locationcode, $city) = explode('-', $filename);
Use PHP explode
$pieces = explode('-', 'species_name-date-locationcode-city');
$name = $pieces[0];
$data = $pieces[1];
$code = $pieces[2];
$city = $pieces[3];
<?php
$myvar = 'common_daisy-20130731-ABCD-Dallas';
$tab = explode ('-', $myvar);
$speciesname = $tab[0];
$date = $tab[1];
$locationcode = $tab[2];
$city = $tab[3];
?>
You can explode the string on delimiter and then assign to variables
$filename = 'species_name-date-locationcode-city';
$array = explode('-', $filename);
$speciesname = $array[0];
$date = $array[1];
$locationcode = $array[2];
$city = $array[3];
http://php.net/manual/en/function.explode.php
$pieces = explode("-", $description);

PHP: uploading a text file and processing on the file content

I have a text file containing data/fields which are separated by exact column no. Each new line represents a new row of data.
Example of file content:
John Chow 26 543 Avenue Street
From the above, first 10 columns are for the name. Next two are for age. And the rest are for the address.
I need to segregate those data from the uploaded file and display it to the user in a formatted table, which will later on be inserted into the database upon confirmation by user.
I am new to PHP. I think substr could work.
Please guide me on how to go about it. I am using codeigniter with PHP, but basic steps in plain PHP will do. Thanks
Read every line of the file, and parse the lines with either substr or regular expression:
$data = array();
$h = fopen($uploadedfile,"r");
while (false !== ($line = fgets($h)))
{
/* substring way: */
$data[] = array(
'name' => trim(substr($line,0,10)),
'age' => intval(sbstr($line,10,2),10),
'address' => trim(substr($line,12))
);
/* regular expression way: */
preg_match("'^(.{10})(.{2})(.*)$'",$line,$n);
$data[] = array(
'name' => trim($n[1]),
'age' => intval($n[2],10),
'address' => trim($n3)
);
}
fclose($h);
Then iterate the $data array to display it in a table form.
Edit: what you ask in the comments can be done also with regular expressions. If $val is the parsed 10 character string, then:
$val = preg_replace("'^0*'","",$val);
would replace all leading 0s.
Yes, you should be using substr. This extracts part of the string. Something like:
$name = trim(substr($line, 0, 10));
$age = trim(substr($line, 10, 2));
$addr = trim(substr($line, 12));
I've added trim to remove any extra whitespace.
Umm I suggest you don't use substr, because peoples names are not always going to be the same length so this will create some problems. I think the explode and implode functions would do the trick better for you, they split a string into an array and back.
http://php.net/manual/en/function.explode.php
http://www.php.net/manual/en/function.implode.php
<?PHP
$str = "John Chow 26 543 Avenue Street";
$data = explode(" ", $str);
$first_name = $data[0];
$last_name = $data[1];
$age = $data[2];
$address = implode(" ", array_slice($data, 3));
?>
You can use a regexp:
if (preg_match('/(.{10})(.{2})(.{12})/', $input, $output)) {
var_dump($output);
}

How to get comma separated values from the string in php

I have a string $employee="Mr vinay HS,engineer,Bangalore";. i want to store Mr vinay H S in $name ,engineer in $job and Bangalore in $location. how to do this
$record = explode(",",$employee);
$name = $record[0];
$job = $record[1];
$location = $record[2];
Use the list function to take the exploded array into 3 variables
list($name, $job, $location) = explode(',', $employee);
list($name,$job,$location) = explode(',',$employee);
Note: this will obviously only work if the string is in the format you specified. If you have any extra commas, or too few, then you'll have problems.
It's also worth pointing out that PHP has dedicated functions for handling CSV formatted data.
See the manual page for str_getcsv for more info.
While explode() is the quickest and easiest way to do it, using str_getcsv() rather than simple explode() will allow you to handle input more complex input, eg containing quoted strings, etc.
explode will do just that I guess
http://php.net/manual/en/function.explode.php
Any more help on this would suffer from givemethecode-ism, so I leave you to it ;-)
list($name,$job,$location) = explode(',',$employee);
Something like the following should work:
//The employee name
$employee= "Mr vinay HS,engineer,Bangalore";
//Breaks each portion of the employee's name up
list($name, $job, $location) = explode(',',$employee);
//Outputs the employee's credentials
echo "Name: $name; Job: $job; Location: $location";
Or you can use another function to do that - http://php.net/manual/en/function.str-getcsv.php
list($name,$job,$location) = str_getcsv($employee);
You can look at the explode() and list() functions:
list($name, $job, $location) = explode(",", $employee);

Categories