0

I have different servers

$strarrServerIp = array('192.168.123.1','192.168.123.2');
$strarrLogsData = array();
foreach($strarrServerIp as $strServerIp ){
       $strCommand = 'ssh abose@' . $strServerIp . ' cat /srv/www/vhosts/trunk/Logs/Log20130825.psi.log';
        $strarrLogsData[] = shell_exec( $strCommand );

            }
foreach( $strarrLogsData as $strJsonLogData ){
           foreach( preg_split("/((\r?\n)|(\r\n?))/", $strJsonLogData ) as $strJsonLineLog ) {
                                display($strJsonLineLog);
                        }
                }

The servers contain files containing JSON logs in this form.

 {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"}
 {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
 {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
 {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
 {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}

I want to separate them into an array

array (
    [0] => {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"}
    [1] => {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
    [2] => {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
    [3] => {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
    [4] => {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}
)

Any suggestions? I want something better than

 preg_split("/((\r?\n)|(\r\n?))/", $strJsonLogData )
Abhishek
  • 270
  • 1
  • 5
  • 16
  • Do you expect to have many rows in that file? Maybe you're better off with reading one line at a time. Or you could just explode on newline. – JimL Sep 09 '13 at 05:51
  • how you read the file content? can you post that part also? –  Sep 09 '13 at 05:52

2 Answers2

1

Try this, you can also use file() function to get each line separated in an array.

$text = '
 {"timestamp":"2013-08-25 20:35:06 MDT","severity":"INFO","data":"1"} {"timestamp":"2013-08-25 20:36:06 MDT","severity":"INFO","data":"15"}
 {"timestamp":"2013-08-25 20:37:06 MDT","severity":"INFO","data":"32"}
 {"timestamp":"2013-08-25 20:38:06 MDT","severity":"INFO","data":"25"}
 {"timestamp":"2013-08-25 20:39:06 MDT","severity":"INFO","data":"5"}';

$array =  preg_split("#}.*?{#s", $text );

$array = array_map("trim", $array);
print_r($array);


//using preg_match_all

preg_match_all("#({.*?})#s", $text, $matches);
print_r($matches[1]);
0

Split by \n and use json_decode on each line.

Tzach
  • 12,889
  • 11
  • 68
  • 115
  • preg_split("/((\r?\n)|(\r\n?))/", $strJsonLogData ) already does that . I want a custom function which will separate even if they are on the same line. – Abhishek Sep 09 '13 at 05:52