Jump to content

fopen multiple files, then select one


aquanuke

Recommended Posts

Hi I want to read multiple .txt files and then if an action requires select one.

 

<?

// /home/person-mike.txt

// /home/person-sarah.txt

// /home/person-paul.txt

 

while ($row = sqlite_fetch_array($result)) {

$name = $row['name'];

 

$filename = "/home/person-$name.txt";

$handle = fopen($filename, "r");

$sendrequest = fread($handle, filesize($filename));

fclose($handle);

}

 

?>

 

<?

if ( $client == "sarah" ) {

echo "$sendrequest[sarah]";

?>

 

How do I do the last bit to have a variable like $sendrequest[sarah]

Link to comment
Share on other sites

Try this:

 

<?php
// /home/person-mike.txt
// /home/person-sarah.txt
// /home/person-paul.txt

$sendrequest = array();
while ($row = sqlite_fetch_array($result)) {
  $name = $row['name'];

  $filename = "/home/person-$name.txt";
  $handle = fopen($filename, "r");
  $sendrequest[$name] = fread($handle, filesize($filename));
  fclose($handle);
}

?>

<?php
if ( $client == "sarah" ) {
   echo "$sendrequest[sarah]";
}

// Or to simplify that last "if" condition:

echo $sendrequest[$client];
?>

Link to comment
Share on other sites

Why are you mixing flat files with a database?

 

Is there any reason in specific you don't have ALL of the data in SQLite?

 

If you are getting the text file from an outside source, it might be a better solution to have an automated script push that data to the DB for you. It will definitely save lines of code and processing time.

 

If this is out of the picture, a solution that takes less memory might go something like this:

<?php 

$client = 'sarah';

if( ($data = getUserFile($client)) === FALSE )
echo 'Unable to find '.$client.'\'s data';
else
echo $data;

function getUserFile( $username ) {
// These could be arguments rather than hard coded
$pre = '/home/person-';
$suf = '.txt';
if( ($data = @file_get_contents($pre.$username.$suf)) === FALSE )
	return FALSE;
return $data;
}

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.