This is my idea on how to turn Shell exec output in PHP to array output. I just want to share it and get feedback in case there is any better way.
Below is a code example to get server info from GCE.
$shell_command = "gcloud compute instances list";
$result = shell_exec($shell_command);
//echo "\n$result\n";
$data = explode("\n",$result);
//print_r($data);
$headers = turn_linux_row_to_array($data[0]);
unset($data[0]);
$servers_array = array();
foreach($data as $row){
$server_data = turn_linux_row_to_array($row,$headers);
if(!empty($server_data)){
$servers_array[] = $server_data;
}
}
//function to move text out put to array
function turn_linux_row_to_array($row,$headers=array()){
$final_data_array = array();
$data_array_position = 0;
$row_length = strlen($row);
$current_word = '';
//echo "\nRow length is :: $row_length\n";
for($i=0; $i<$row_length; $i++){
$char = substr( $row, $i, 1 );
if($char != ' '){
//This is a part of a value
$current_word .=$char;
}else{
if($current_word!=''){
if(!empty($headers) && isset($headers[$data_array_position]) ){
$final_data_array[$headers[$data_array_position]] =
$current_word;
}else{
$final_data_array[] = $current_word;
}
$data_array_position++;
}
$current_word = '';
}
}
//print_r($final_data_array);
return $final_data_array;
}