parsing a text file in php and retrieving information - php

I'm trying to parse a basic text file in PHP, but not sure where to begin.
The file contains info such as:
http://pastebin.com/ahqtJzH6
You'll notice that the information I need to capture is split up by new lines. Right now I'm just throwing every new line into a $applicant[] array, but I need to get rid of the preceding text in each line.
I was thinking I probably need to use regex or something to single out just the data I need. Ideas?
Thank you!

Without using regex, you can do this:
$fp = fopen('textfile.txt', 'r');
$return = array();
while ($line = fgets($fp)) {
$parts = explode(':', $line);
$key = trim($parts[0]);
unset($parts[0]);
$value = str_replace("\n", '', implode(':', $parts));
$return[$key] = trim($value);
}
print_r($return);
Would output something like:
Array (
[Applicant SSN] => 123456789
[Applicant Name] => BOB, BOB
...
)

You could use strpos to find the : character and then grab everything after that. You can use trim to get rid of extra whitespace.
$lines = file('textfile.txt');
foreach ($lines as $line) {
$p = strpos($line, ':');
if ($p!==false) {
$key = trim(substr($line, 0, $p));
$value = trim(substr($line, $p+1));
// do whatever with your key & value
}
}

Related

PHP file with multiple lines to array and key with value

I have files with lines in it where i want to create array with a key and value
file1 has for example:
thisisline = aline
thisisalsoaline = oke
whereiamaline = check
file2 has
thisisline = aline
thisisalsoaline = oke
whereiamaline = checker
what i am trying to create but no luck to have a result which is :(
thisisline => aline
thisisalsoaline => oke
whereiamaline => check
i tried with explode but then it was like
[0] => thisisline = aline
the endgoal is to have 2 files to compare with array_diff_key so that i can identify the line whereiamaline = checker
Could somebody point me to the correct direction?
Thank you
Your files look like ini-files. php already has parse_ini_file function, which will return key => value array.
Next, correct function is array_diff_assoc:
$a = parse_ini_file('file1');
$b = parse_ini_string('file2');
print_r(array_diff_assoc($a, $b));
Because array_diff_key returns keys which are in first array, but not in second, which is not your case.
You can do it with explode function with delimeter =, like:
$finall_array = array();
$handle = fopen("file.txt", "r");
if ($handle) {
while (($line = fgets($handle)) !== false) {
$le = explode("=",$line);
$finall_array[$le[0]] = $le[1];
}
fclose($handle);
} else {
// here goes error file opeping
}
Then just use $final_array like your output
You can do it this way.
foreach(file("file1.txt") as $line) {
$pieces = explode("=", $line);
//Do whatever you want to do with $pieces here. $pieces[0] and $pieces[1]
//Trim the values of $pieces too.
}
Another way is:
for each(file("file1.txt") as $line) {
$res[] = array_map('trim', explode('=', $line));
}
This one will directly populate the $res[] array with arrays of each line (which are trimmed)
So i used the parse_in_file together with the arra_diff_assoc and then it is
<?php
$file1 = parse_ini_file("master_manager.txt");
$file2 = parse_ini_file("master_manager1.txt");
echo "<pre>";
$myarray = array_diff_assoc($file1, $file2);
foreach ($myarray as $key => $value){
echo $key." = ".$value."\n"; }
echo "</pre>";
but then if a line contains false or true it gives a 1 or nothing (null) how to prevent that? –

Change Plain Text To JSON Array

I am getting the following data from a file_get_contents php://input
transfer_date:2018-02-14 content:1000_102eabca374092d1e97daf0bf52e9d count:1
transfer_date:2018-02-13 content:1000_1022e2297c8e9e1a18743182e4f265 count:0
transfer_date:2018-02-13 content:1000_10254e35fda57121d48bd71693c500 count:0.5
transfer_date:2018-02-12 content:102ead3122a4c8742bff97fcc46b38 count:0.5
transfer_date:2018-02-12 content:1000_102ee58d8e12eadbce86d526607164 count:0.5
Any ideas on how to turn this into a json array?
I want the data in format
"transfer_date":"2018-02-14","content":"123445585989898","count":"1"
so I can run it through a for each.
I have tried on the values but it only gets me halfway there and I can keep using find replace but there must be another way no?:
//$datatwo = str_replace('transfer_date: '"transfer_date":"',"$datatwo");
You can use regex to get not-space symbols before and after colon
$arr = array_map(function($x) {
if (preg_match_all('/(\S+):(\S+)/',$x, $m)) {
return array_combine($m[1], $m[2]);
}
}, file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES));
echo json_encode($arr, JSON_PRETTY_PRINT);
demo
i'm not sure, but i guess this would work for you.
<?php
$input = file('php://stdin', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$transfers = [];
foreach($input as $line) {
$transfer=[];
// break the white space between key=value so each key/value get added alone
$parts = explode(' ',$line);
foreach($parts as $part) {
// separate the key and value
$values=explode(':',$part);
$transfer[ $values[0] ] = $values[1] ?? null;
}
// add to the result
$transfers[]= $transfer;
}
// print json encoded result
echo json_encode($transfers);
Simpliest you could do if the there are only spaces between fields and colons as key/value separator:
$data = ''; //your data
$data = str_replace("\r\n", "\n", $data); //remove carriage return
$lines = array_filter(explode("\n", $data)); //split your data by new line and filter empty lines
$rows = [];
foreach ($lines as $line) {
$fields = explode(' ', $line); //explode the content of a line by space to get all fields
foreach ($fields as $field) {
$fieldParts = explode(':', $field); //explode a field to get key and value
$rows[$fieldParts[0]] = $fieldParts[1]; //assign it to your result array
}
}
var_dump(json_encode($rows));

Php get value from text file

I have this textfile:
foo: bar
el: macho
bing: bong
cake color: blue berry
mayo: ello
And I what I'm trying to accomplish is that if I "look" for foo, it returns bar (if I look for bing, it should return bong). A way a tried to accomplish this is first search though the file, return the line with the result, put it in a string and remove everything before the ":" and display the string.
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false)
echo $line;
$new_str = substr($line, ($pos = strpos($line, ',')) !== false ? $pos + 1 : 0);
}
echo "<br>";
echo "bing should return bong:";
echo $new_str;
But it doesn't work. Up here is just one of the many things I've tried.
Sources:
Many stackoverflow links on and comparable searches:
https://www.google.com/search?client=opera&q=php+remove+everything+after
https://www.google.com/search?client=opera&q=php+search+text+file+return+line
I've asked a question before, but the answers are to "professional" for me, I really need a noob-proof solution/answer. I've been trying to figure it out all day but I just can't get this to work.
Edit:
It's solved! Thank you so much for your time & help, I hope this might be useful to someone else to!
This should work with what you are looking for, I tested it on my server and it seems to fit what you are looking for.
$lines_array = file("file.txt");
$search_string = "bing";
foreach($lines_array as $line) {
if(strpos($line, $search_string) !== false) {
list(, $new_str) = explode(":", $line);
// If you don't want the space before the word bong, uncomment the following line.
//$new_str = trim($new_str);
}
}
echo $new_str;
?>
I would do it this way:
foreach($lines as $line)
{
// explode the line into an array
$values = explode(':',$line);
// trim the whitspace from the value
if(trim($values[1]) == $search)
{
echo "found value for ".$search.": ".$values[1];
// exit the foreach if we found the needle
break;
}
}
$search = 'bing';
// Read from file
$lines = file('text.txt');
$linea='';
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false) {
$liner=explode(': ',$line);
$linea.= $liner[1];
}
}
echo 'Search returned: '. $linea;
Explanation: - $linea var is created before loop, and it will contain search result. If value is found on line - explode string, and make array, get second var from array, put it in search results container variable.
As your data is almost YAML [see lint], you could use a parser in order to get the associated PHP array.
But if can go with your solution as well:
// What to look for
$search = 'bing';
// Read from file
$lines = file('file.txt');
foreach($lines as $line)
{
// Check if the line contains the string we're looking for, and print if it does
if(strpos($line, $search) !== false){
echo array_pop(explode(":", $line));
}
}
Use fgetcsv:
$bits = array();
if (($handle = fopen('t.txt','r')) !== FALSE) {
while (($data = fgetcsv($handle, 0, ":")) !== FALSE) {
$bits[$data[0]] = $data[1];
}
}
# Now, you search
echo $bits['foo'];
$bits will have a key for each split part, which makes your ultimate goal quite simple. Here is what it looks like:
Array
(
[foo] => bar
[el] => macho
[bing] => bong
[cake color] => blue berry
[mayo] => ello
)

Search a file in PHP for a string and return the next line

I have a file I am reading in with php:
$lines = file("input.txt");
I need to search $lines for the string --><-- then return the very next full line. What is the best way to do this?
Thanks.
You should loop through the array $lines and increment the key by 1 to get the next line.
$lines = file("input.txt");
$return = array();
foreach($lines as $key => $line) {
if(false !== strpos($line,'--><--')) {
// check if there is another line in the file
if(isset($lines[($key+1)])) {
// add the line to array
$return[] = $lines[($key+1)];
}
}
}
print_r($return);
I wasn't sure if you were matching a Windows or a Unix file (hence the \r?), but you can do it with Regular Expressions much more cleanly. You can capture it like this:
$lines = file("input.txt");
preg_match('!(--><--\r?\n)([^\r\n]+)\r?\n!s',$lines,$matches);
$myLine = $matches[2];
echo $myLine;

PHP get a string into a associative array

I've got a variable going like this(in the original list there no whitespace):
http://www.iso.org/iso/list-en1-semic-3.txt
$country ="
ÅLAND ISLANDS;AX
ALBANIA;AL
ALGERIA;DZ
";
(going on and on in the same order)
I like to put this in a array going like this:
array: [Åland Islands] ==> AX
[Albania] ==> AL
[Algeria] ==> DZ
I've try to use php explode but that doesn't work, my knowledge is to basic to get it right. Who can help?
print_r(explode(';', $country));
This will get you where you're going:
$output = array();
// break it line-by-line
$lines = explode('\n', $country);
// iterate through the lines.
foreach( $lines as $line )
{
// just make sure that the line's whitespace is cleared away
$line = trim( $line );
if( $line )
{
// break the line at the semi-colon
$pieces = explode( ";", $line );
// the first piece now serves as the index.
// The second piece as the value.
$output[ $pieces[ 0 ] ] = $pieces[ 1 ];
}
}
$result = array();
$lines = explode(PHP_EOL, $country);
foreach ($lines as $line) {
$line = explode(';', $line);
$result[array_shift($line)] = array_shift($line);
}
$a = explode("\n", $country);
$result = array();
foreach($a as $line) {
list($x,$y) = explode(";", $line);
$result[$x] = $y;
}
Note: remove extra empty lines from $country or check for empty lines.

Categories