John Davidson

How to make PHP to handle multiple lines output?

0 comments
Message:


I'm struggling with this for a day now...
I have an OS command that returns several lines of output:


root@downloader:/var/www/html# /usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0
Voltage: 248.00 V
Current: 16.29 A
Power: 4000.40 W
Active Apparent Power: 4014.28 VA
Reactive Apparent Power: -339.60 VAR
Power Factor: 1.00
Phase Angle: 0.00 Degree
Frequency: 50.00 Hz
Import Active Energy: 22726178 Wh
Export Active Energy: 252806 Wh
Total Active Energy: 22978984 Wh
Import Reactive Energy: 1136648 VARh
Export Reactive Energy: 2343577 VARh
Total Reactive Energy: 3480225 VARh
OK

I'm now trying to get this output via web through a simple PHP script, so I'm doing:


<?php
echo (exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0'));
?>

However, the result is always "OK", which is the last line of the output.


My first idea was to "grep" the needed info in the OS command, and run it multiple times as needed, like:


echo (exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0 | grep -i Power:'));


and it would suffice if I just needed one line of output.
The problem is that I can't run the OS command more often than once every 3 or 4 seconds, so since I need multiple lines, I can't really use this alternative...


Any idea how to get all the OS command output to be shown in the PHP request?



My Answer:
You can use the `shell_exec` function in PHP to capture the entire output of the command, including multiple lines. Here's an example of how you can modify your PHP script to capture and display the entire output:

php
$output = shell_exec('/usr/local/bin/sdm120c -a 1 -P N -S 2 -j 20 /dev/ttyUSB0');
echo nl2br($output);
?>


In this script, the `shell_exec` function is used to capture the entire output of the command. The `nl2br` function is then used to convert newline characters in the output to HTML `
` tags, so that the output is displayed with line breaks in the browser.

This should allow you to display all the lines of output from the OS command in your PHP script.

Rate this post

3 of 5 based on 6259 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us