PDA

View Full Version : Help with PHP and reading text in to page from file




edesignuk
Oct 27, 2009, 05:14 AM
I can just about struggle though with PHP (and I have been), but now I'm stuck.

Here's what I'd like to do...

I have this in a text file on the web server local drive. Say C:\Logs\Expire.txt:

"cn=surname1\, firstname1 (company),ou=users,dc=domain,dc=net"
"cn=surname2\, firstname2 (company),ou=users,dc=domain,dc=net"
"cn=surname3\, firstname3 (company),ou=users,dc=domain,dc=net"

I'd like to read this file from a web page using PHP, and display the file like this:
surname1, firstname1
surname2, firstname2
surname3, firstname3
So I need to manipulate the file a little, trim out some stuff, but I have no idea how.

Any ideas?

Thank you!



trule
Oct 27, 2009, 05:32 AM
http://www.google.com/search?client=safari&rls=en&q=php+read+line+from+file+and+split&ie=UTF-8&oe=UTF-8

and

http://php.net/manual/en/function.explode.php

edesignuk
Oct 27, 2009, 05:48 AM
Thank you.

I'm sure between those I can do what I want, but if you could, would you mind explaining how exactly? (the code).

robbieduncan
Oct 27, 2009, 06:03 AM
Big-Ass-Warning: I don't use PHP at all. I am tackling this like a Perl programmer!

I'd use preg_match_all

Something like:


preg_match_all("cn=(.*)\\, (.*).*",$line,$matches);


Assuming $line contains a single line as below then $matches should be a two element array with the first element containing the surname, the second element the first name.

SrWebDeveloper
Oct 27, 2009, 08:22 AM
@OP:

Tested with your data, works:

// Read the file from disk and put contents into $data - adjust path and filename...
$filename = $_SERVER['DOCUMENT_ROOT']."/test.txt";
$handle = fopen($filename, "r");
$data = fread($handle, filesize($filename));
fclose($handle);

// Create an array holding each line (determined by newlines terminator)..
$lines_arr=explode("\n",$data);

// Process each line of data...
foreach ($lines_arr as $line) {
// Correct regular expression, extract matches into $matches array for this line...
preg_match_all("/cn=(.*?)\\\, (.*?) \(.*?/i",$line,$matches,PREG_SET_ORDER);
// Display final output walking through $matches array for this line...
foreach ($matches as $parsed) {
print "$parsed[1], $parsed[2]<br />";
}
}


Instead of making a string holding your data, I created a disk file and made sure a newlines (carriage return) separated each line.

I used both explode and preg_match_all (adjusting the expression posted by the other user, this one works) to demonstrate how each works in PHP and added comments to explain each segment of code. Obviously use your own filename and path and add in necessary code to check if the data file exists and if matches is null, etc., as would be done in production code.

-jim

edesignuk
Oct 27, 2009, 08:26 AM
^ Exactly what I was after, thank you!