Re: looping and writing to a file
Available news archives: comp.lang.tcl - comp.lang.python - comp.security.firewalls - sci.crypt - comp.lang.php - comp.lang.javascript
Google
 
Web news.hping.org


comp.lang.php archive

Re: looping and writing to a file

From: Ken Robinson <kenrbnsn@rbnsn.com>
Date: Mon Jul 18 2005 - 06:11:37 CEST

Aaron Reimann wrote (in part):
> I have a function here that will (with some other functions not shown
> here) display some results from a database. Here is the code:
>
> function display_song_list($fd, $e) {
> global $sys_install_base;
> global $sys_relative_uploaddir;

You know you can write those two lines on one line.

       global $sys_install_base, $sys_relative_uploaddir;

>
> echo ("<songs>\n");
>
> foreach ($e as $error) {
> echo ("$error\n");
> }
>
> $c = pg_numrows($fd['result']);
> for ($i = 0; $i < $c; $i++) {
> $r = pg_fetch_assoc($fd['result'], $i);
>
> echo ("<song title=\"{$r['song_title']}\" artist=\"{$r['artist']}\"
> path=\"{$sys_install_base}{$sys_relative_uploaddir}{$r['audio_file']}\"/>\n");
>
> }
>
> echo ("</songs>");
>
> }
>

You don't need parenthesis on an echo statement.

> I need some help writing the info to a text file. I know the 'fopen'
> and 'fwrite' stuff. But I don't how to write <songs>, and then write
> out all of the rows from the database, and then write </songs>.

If you know about fopen and fwrite, what's your problem?

$fp = fopen('your.file','w');
fwrite($fp, 'this is a line'."\n");
fclose($fp);

Just replace your echo statements with fwrite statements and make sure
you end each line with a carriage return ("\n").

BTW, this echo statement:

 echo ("<song title=\"{$r['song_title']}\" artist=\"{$r['artist']}\"
path=\"{$sys_install_base}{$sys_relative_uploaddir}{$r['audio_file']}\"/>\n");

can be written much more cleanly, something like:

echo '<song title="' . $r['song_title'] .'" artist="' . $r['artist'] .
'" path="' . $sys_install_base . $sys_relative_uploaddir .
$r['audio_file'] . '"/>' . "\n";

Ken
Received on Mon Oct 17 21:09:47 2005