note 17523 added to function.exec

From: Date: Wed, 12 Dec 2001 20:40:32 +0000
Subject: note 17523 added to function.exec
Groups: php.notes 
Request: Send a blank email to php-notes+get-22556@lists.php.net to get a copy of this message
Getting exec() command results into the related array (Watch out for HEX 0A 00) I had a need to use exec to grab the results of a command that would normally go to stdout. So I first try a simple command like "ping", this works fine as below, showing each line of the ping command. // This works fine $command = "ping -c5 localhost"; exec ($command, $results); $maxidx = count ($results); for ($idx = 0; $idx < $maxidx; ++$idx) { echo ("Line $idx contains: $results[$idx] <BR>\n"); } Now, I want grab the contents of a plain text file into the array. The below command does not work as expected, it results in one blank (null) array member for each line of text. A 100 line text file gets you 100 blank array items. The same is true of the file("somefile.txt") command. // This get you an array of nulls $command = "cat somefile.txt"; exec ($command, $results); $maxidx = count ($results); for ($idx = 0; $idx < $maxidx; ++$idx) { echo ("Line $idx contains: $results[$idx] <BR>\n"); } So I checked the hex values of the plain text file. Turns out that each line starts with HEX 0A 00, a line feed and a null. This can be seen by doing "cat -A somefile.txt". It is understandable that the exec() array loading routine sees HEX 0A 00 and gets a blank line, certainly not what I want or expected. Knowing this quirk, I can then deal with it. Turn those non-printable HEX characters into printable ones I can control and work around. This works: // This get you an array of text, each line starting with ^@ ending with $ $command = "cat -A somefile.txt"; exec ($command, $results); $maxidx = count ($results); for ($idx = 0; $idx < $maxidx; ++$idx) { echo ("Line $idx contains: $results[$idx] <BR>\n"); } Sure would be nice to be able to control the way exec() loads the array with a hex switch or something. -- http://www.php.net/manual/en/function.exec.php http://master.php.net/manage/user-notes.php?action=edit+17523 http://master.php.net/manage/user-notes.php?action=delete+17523 http://master.php.net/manage/user-notes.php?action=reject+17523

« previous php.notes (#22556) next »