I have two files that I need opened, I'm using php file to read them
$lines = file('/home/program/prog_conf.txt');
foreach ($lines as $line) {
$rows = preg_split('/\s+/', $line);
Followed by:
$lines = file('/home/domain/public_html/base/file2.cfg');
foreach ($lines as $line) {
$rows = preg_split('/=/', $line);
As I work with these two files, I need to pull info from the second one, which I seperated by =, however, I'm not sure this is the best thing to do. I wanted to add data checking from the database. The db details are in the second file like so:
dbname = databasename
dbuser = databaseuser
dbpass = databasepassword
If I echo the $rows[2], I get everything all the information I need on a single line, not on seperate lines. Meaning:
databasename databaseuser databasepassword
How do I split the information up so I can use the entries one by one?
How about:
$lines = file('/home/domain/public_html/base/file2.cfg');
$all_parts = array()
foreach ($lines as $line) {
//explode pulls apart a string based on the first value, so you could change that
//to a '=' if need be
array_merge($all_parts,explode(' ', $line));
}
This would get you all the parts of the file, one at a time, into an array. Which is what I think you wanted.
If not, just explode as needed
Maybe this aproach helps:
First as i see your second file has multiple lines, so what would do is something like this:
Assumin that every key as "db" in common we can do something like this.
$file = fopen("/home/domain/public_html/base/file2.cfg", "rb");
$contents = stream_get_contents($handle); // This function return better performance if the file isn't too large.
fclose($file);
// Assuming this is your return from the file
$contents = 'dbname = databasename dbuser = databaseuser dbpass = databasepassword';
$rows = preg_split('/db+/', $contents); // Splinting keys "db"
$result = array();
foreach($rows as $row){
$temp = preg_replace("/\s+/", '', $row); // Removing extract white spaces
$temp = preg_split("/=/", $temp); // Splinting by "="
$result[] = $temp[1]; // Getting the value only
}
var_dump ($result);
I hope this help you can try this code maybe with little modifications but works.
Related
I am having a file like settings.txt.
which contains some lines like
SET VERSION=3
SET BACKUP_DRIVE=D:\
SET BACKUP_DIRECTORY=BACKUP\
SET HOURLY_DIRECTORY=HOURLY\
SET INPUT_DIRECTORY=C:\MySQL\Data\CDR\
SET username=username
SET password=password
this file is at other location or on other server. I have get this file using ...
$frserver = file_get_contents("http://ip is here/cdr/settings.txt");
I used this
$File = file_get_contents("http://ip is heresettings.txt");
$FileArr = explode("\r\n",$File);
echo $FileArr[5]; // This will output: SET username=desired username
and get "SET username=desired username" bt i want only "desired username"..just this issue left nw
Now I am unable to get username and password from it.
how to get username and password so i can compare them in db...
Assuming
$frserver = 'SET VERSION=3
SET BACKUP_DRIVE=D:\
SET BACKUP_DIRECTORY=BACKUP\
SET HOURLY_DIRECTORY=HOURLY\
SET INPUT_DIRECTORY=C:\MySQL\Data\CDR\
SET username=username
SET password=password';
the whole solution is just these 2 lines:
preg_match_all('~^SET\s+([^=]+)=(.*)$~m', $frserver, $matches);
$params = array_combine($matches[1], $matches[2]);
So after that you can retrieve your variables as $params['username'] and $params['password'] correspondingly.
Live example on ideone: http://ideone.com/pn2Wbp
$File = file_get_contents("Settings.txt");
$FileArr = explode("\r\n",$File);
echo $FileArr[5]; // This will output: SET username=username
Explained:
This code will break up the contents of the file specified by new line breaks represented by \r\n which is the windows format for new line.. HTML equivalent: <br>
To See the full array:
print_r($FileArr);
If you just need to get data from a text file, I recommend using a csv, like this:
key,value
VERSION,3
BACKUP_DRIVE,D:\
BACKUP_DIRECTORY,BACKUP\
HOURLY_DIRECTORY,HOURLY\
INPUT_DIRECTORY,C:\MySQL\Data\CDR\
username,username
password,password
Then you can do something like this to get all these keys and values into a PHP array:
$contents = file_get_contents('http://ip is here/cdr/settings.txt');
$lines = explode("\n",$contents);
foreach($lines as $line) {
$pair = str_getcsv($line);
$settings[] = array($pair[0]=>$pair[1]);
}
// print_r to see the array
print_r($settings);
You are probably best served using file() to fetch the data, such that the data returned is in an array already (one element per line of text):
$raw_array = file('http://ip is here/cdr/settings.txt');
Then perhaps run an array walk to set everything to a usable array
$final_array = array();
array_walk($raw_array, function($value) use $final_array {
$value = trim($value); // trim newlines
$value = str_replace('SET ', '', $value); // remove 'SET '
$value_array = explode('=', $value); // break up value on '='
$final_array[$value_array[0]] = $value_array[1]; // set key/value in $final_array
});
For PHP version < 5.3 where there is not support for anonymous functions, you need to use a named function here, so it might look like this:
$final_array = array();
array_walk($raw_array, 'parse_raw_array', $final_array);
function parse_raw_array ($value, $key_not_used, $final_array) {
$value = trim($value); // trim newlines
$value = str_replace('SET ', '', $value); // remove 'SET '
$value_array = explode('=', $value); // break up value on '='
$final_array[$value_array[0]] = $value_array[1]; // set key/value in $final_array
});
Then simply access key/values from $final_array as needed
$username = $final_array['username'];
$password = $final_array['password'];
That being said, passing your MySQL credentials (I assume that is what this is) in the clear like that is probably not a great idea.
Is there an easy way to parse the following data that I will post below. The data comes from the web.
I was using the $rows = explode("\n", $txt_file); then the $parts = explode('=', $line_of_text); to get the key name and values. However, I don't know how to handle the extra information that I do not want.
Additionally, I do not know how to get rid of the extra spaces. The file seems to be made for some kind of easy parsing. I have looked all over this site to find a solution. However, this data is quite different than the examples I have found on this site.
# This file holds all the timelines available at this time.
# All lines starting with # is ignored by parser...
#
STARTINFO
description = Rubi-Ka 2
displayname = Rimor (Rubi-Ka 2)
connect = cm.d2.funcom.com
ports = 7502
url =
version = 18.5.4
ENDINFO
STARTINFO
description = Rubi-Ka 1
displayname = Atlantean (Rubi-Ka 1)
connect = cm.d1.funcom.com
ports = 7501
url =
version = 18.5.4
ENDINFO
You can use the trim function to get rid of the whitespace.
To only keep the columns you want, you can store their keys in an array, and make a check against it when parsing.
Here's an example (albeit rather verbose).
<?
$lines = explode("\n", $data);
$result = array();
$count = 0;
// an array of the keys we want to keep
// I have the columns as keys rather then values for faster lookup
$cols_to_keep = array( 'url'=>null, 'description'=>null, 'ports'=>null, 'displayname' => null);
foreach($lines as $line)
{
//skip comments and empty lines
if(empty($line) || $line[0] == '#')
{ continue; }
//if we start a new block, initalize result array for it
if(trim($line) == 'STARTINFO')
{
$result[$count] = array();
continue;
}
// if we reach ENDINFO increment count
if(trim($line) == 'ENDINFO')
{
$count++;
continue;
}
//here we can split into key - value
$parts = explode('=', $line);
//and if it's in our cols_to_keep, we add it on
if(array_key_exists(trim($parts[0]), $cols_to_keep))
{ $result[$count][ trim($parts[0]) ] = trim( $parts[1] ); }
}
print_r($result);
?>
I need help to solve this problem:
I have a csv file like this
hello,ciao
goodbye,arrivederci
as you can see I try to create a translation system for a site
now I want this csv file into an array, the resultant array must be the same of $langArray
<?php $langArray = array([it]=>array([hello]=>ciao,[goodbye]=>arrivederci)); ?>
I already have a solution using a Json file to have an array like this, and is most usefull that a csv file and I can use translation system also with javascript. but I want to know the way to do that with a csv file thank you
For reading a CSV file you should use fopen and fgetcsv, or for the short version str_getcsv (needs current PHP or compat library):
$csv = array_map("str_getcsv", file("it.csv"));
Then building the associative map requires a manual loop:
foreach ($csv as $line)
$translate["it"][ $line[0] ] = $line[1];
You could use explode to split your data once for the new line, then once for the comma, and fill an array with it.
<?php
$translations = array();
$data = 'hello,ciao
goodbye,arrivederci';
$words = explode("\n", $data);
foreach($words as $w) {
$parts = explode(',', $w);
$translations[$parts[0]] = $parts[1];
}
print_r($translations);
?>
http://codepad.viper-7.com/gCKoI9
<?php
$languageArray = ARRAY();
$my_csv_it = 'hello,ciao goodbye,arrivederci';
$tmp_array_it = explode(' ', $my_csv_it);
foreach ($tmp_array_it AS $text) {
$pairs = explode(',',$text);
$languageArray['it'][$pairs[0]] = $pairs[1];
}
print_r ($languageArray);
?>
I have a CSV file which needs some additional processing. I've got most of our custom functionality completed. My stuck at the moment is the latest addition to the feed, multiple categories in 1 column. Here is a quick example of the new field setup.
Category01#Things~Category01#Will~Category01#Be~Category01#Here~Category02#Testing~Category02#More text here~Category02#Any data~Category02#No more data for this category~LastCategory#This~LastCategory#Is~LastCategory#The~LastCategory#End
I would need to build an array in PHP from each category available, similar to;
$category01 = array('Things', 'Will', 'Be', 'Here');
Any help would be greatly appreciated. Thanks!
If I understand your question and the format correctly, categories separated by ~, and each listed as "SomeString#Category Name", then this should to the trick. However I don't think this has anything to do with the CSV format.
$pairs = explode('~', $string);
$cats = array();
foreach ($pairs as $pair) {
list($cat_number, $cat_name) = explode('#', $pair);
$cats[] = $cat_name;
}
Gahhh. the goggles, they do nothing!
If you're unable to change that output form (and it SHOULD be changed to something nicer), you'll have to go brute force:
$csv = '...';
$categories = array();
$parts = explode('~', $csv);
foreach($parts as $part) {
$bits = explode('#', $part);
$category = (int)substr($part[0], 8);
if (!is_array($categories[$category])) {
$categories[$category] = array();
}
$categories[$category][] = $part[1];
}
Of course, this'll blow up on your LastCategory stuff at the tail end of that "csv". so... let me again STRONGLY urge you fix up whatever's generating that so-called "csv" in the first place.
I have a 12 XML files from which I am extracting ONE CSV file, from which - I am extracting column 1 and appending values to a tt.txt file .
NOW, I need to extract the values from this .txt file... everytime data is written to it ...
But the problem is , when I use
$contents = fread ($fd,filesize ($filename));
fclose ($fd);
$delimiter = ',' ;
$splitcontents = explode($delimiter, $contents);
IT reads ONLY from the first value of the file , every time a tt.txt file is appended !
I hope u understand the problem .. What I need is , I want $contents to have only the new data that was appended... instead it reads from the start of the file everytime...
Is there a way to achieve this, or does php fail ?/
This prob is extraction from TXT file- > performing computations- > writing INTO a new txt file . The problem being that I can't read from a middle value to a new value.. PHP always reads from the start of a file.
I think you need to store the last file position.
Call filesize to get current length, read the file, later, check if filesize is different (or maybe you know this some other way, and use fseek to move the cursor in the file, then read from there.
IE:
$previousLength = 0;
// your loop when you're calling your new read function
$length = filesize($filename);
fseek($fd,$previousLength);
$contents = fread($fd,$length - $previousLength);
$previousLength = $length;
It is only reading the first field because PHP does not automatically assume that a newline character (\n) means a new record; you have to handle this, yourself.
Using what you already have, I would do the following:
$contents = fread($fd, filesize($filename));
close($fd);
/* Now, split up $contents by newline, turning this into an array, where each element
* is, in effect, a new line in the CSV file. */
$contents = explode("\n", $contents);
/* Now, explode each element in the array, into itself. */
foreach ($contents as &$c) {
$c = explode(",", $c);
}
In the future, if you want to go line-by-line, as you run the risk of hogging too many resources by reading the entire file in, use fgets().
I'm not great at arrays but it sounds to me like you need an associative array (I'm doing a similar thing with the following code.
$lines = explode("\n", $contents);
foreach ($lines as $line) {
$parts = explode(',', $line);
if (count($parts) > 0) {
$posts = array();
$posts[] = array('name' => $parts[3],'email' => $parts[4],'phone' => $parts[5],'link' => $parts[6],'month' => $parts[0],'day' => $parts[1],'year' => $parts[2]); }
foreach ($posts as $post):
$post = array_filter(array_map('trim', $post));