Grant
Grant

Reputation: 1337

Writing the results of this PHP script to a text file

I don't even know if this is possible, so feel free to shoot me down if it's a silly question, but I can't think of a way to do it.

This is my script which grabs data from the database and formats the results how I want them :

$users = get_users('user_login', 'display_name', 'ID');

echo 'users: [ ';
$n = count($users);
foreach ($users as $i => $user) {

echo '{ name: "'.$user->user_login.'"';
echo ' username: "'.$user->display_name.'"';
echo ' image: "'.$user->ID.'" }';
if (($i+1) != $n) echo ', ';
}
echo '] ';

Which basically spits out the following when run directly :

users: [ { name: "007bond" username: "James Bond" image: "830" }, { name: "4Tek" username: "4Tek" image: "787" } ]

But instead of running this script when I need it (which will be a lot) I'd like to write the results of this script to a text file.

Is this possible?

Upvotes: 1

Views: 1031

Answers (3)

Denis Rybakov
Denis Rybakov

Reputation: 56

You can use a several ways to write text to file.
1. Without php, just redirect script output to specific file like this:

# php yourfile.php > result.txt

And then you have a result in result.txt.

  1. With php a possible way:
    $users = get_users('user_login', 'display_name', 'ID');

    $text = 'users: [ ';

    $n = count($users);
    foreach ($users as $i => $user) {
       $text .=  '{ name: "'.$user->user_login.'"';
       $text .= ' username: "'.$user->display_name.'"';
       $text .= ' image: "'.$user->ID.'" }';
       if (($i+1) != $n) $text .= ', ';
    }
    $text .= '] ';

    file_put_contents( 'result.txt', $text );

Upvotes: 1

zod
zod

Reputation: 12437

You can do this way too . just incase

$fp = fopen('data.txt', 'w');
foreach ($users as $i => $user) {

fwrite($fp, 'whatever');
}
fwrite($fp, 'anything');

fclose($fp);

Upvotes: 0

LTasty
LTasty

Reputation: 2008

You can use fopen and fwrite

$users = get_users('user_login', 'display_name', 'ID');

$string= 'users: [ ';
$n = count($users);
foreach ($users as $i => $user) {

    $string.= '{ name: "'.$user->user_login.'"';
    $string.= ' username: "'.$user->display_name.'"';
    $string.= ' image: "'.$user->ID.'" }';
    if (($i+1) != $n) $string.= ', ';
}
$string.='] ';

$my_file = 'file.txt';
$handle = fopen($my_file, 'w') or die('Cannot open file:  '.$my_file);
fwrite($handle, $string);

Upvotes: 0

Related Questions