TalkPHP

TalkPHP (http://www.talkphp.com/forums.php)
-   Absolute Beginners (http://www.talkphp.com/absolute-beginners/)
-   -   Make array with txt file content (http://www.talkphp.com/absolute-beginners/3133-make-array-txt-file-content.html)

Peuplarchie 07-16-2008 06:16 PM

Make array with txt file content
 
Good day to you all,
Here is a piece of code from my login script.

PHP Code:


$data
=array("user1"=>array("url"=>"Index/admin-index.php","password"=>"pass1"),
            
"user2"=>array("url"=>"file2.php","password"=>"pass2")); 

As you can see the array is not a generated array, in other word, the script should read a txt file, each line would have, a password, username and a url.
like :
Jack=>Daniel=>Director/index.php
Angolina=>Joli=>Pretty/index.php
Mike=>Lee=>User/index.php

Thanks !
Franck

xenon 07-16-2008 08:28 PM

You could use fscanf...

Ross 07-17-2008 06:27 PM

I would use explode to do this, although fscanf looks a lot easier - I've never seen it before and I'd recommend it now!

PHP Code:

<?php

/**
 * Explode method
 */

// First explode the file into seperate lines and loop through to remove empty lines, etc
$file file_get_contents('file.txt');
$file explode("\n"$file);

$lines = array();

foreach(
$file as $line)
{
     
// Checks a line is not empty (after whitespace is removed) or not a comment (using .ini style comments)
     
if(!empty(trim($line)) && substr($line01) != ';')
     {
          
$lines[] = trim($line);
     }
}

// Next parse the data from the line and add to the $data array
$data = array();
foreach(
$lines as $line)
{
     
$line explode('=>'$line);
     
// Check the line is an array and hasn't done something silly
     
if(is_array($line))
     {
          
$data[] = $line;
     }
}

print_r($data);


/**
 * fscanf method
 */
$file fopen('file.txt''r');

$data_array = array();

while(
$data fscanf($file'%s=>%s=>%s'))
{
     list(
$name1$name2$file) = $data;
     
     
// Example
     
$data_array[$name1] = array($name2$file);
}

fclose($file);

print_r($data_array);

?>

As you can see the explosion method is much more memory intensive but shows you how a file could be parsed. fscanf is much more simple to use.


All times are GMT. The time now is 09:08 AM.

Powered by vBulletin® Version 3.6.8
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.1.0