Search code examples
phpfopenfwrite

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?


Solution

  • 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);