2015-10-12 3 views
1

У меня есть файл журнала "file.log". Я попытался проанализировать файл в php, чтобы получить пару значений ключа.Анализ файла журнала

Notification: { 
"state" : "PROGRESSING", 
"version" : "2012-09-25", 
"jobId" : "xxxxxxxxx", 
"pipelineId" : "xxxxxxxxxxx", 
"input" : { 
    "key" : "upload2/xxxxx", 
    "frameRate" : "auto", 
    "resolution" : "auto", 
    "aspectRatio" : "auto", 
    "interlaced" : "auto", 
    "container" : "auto" 
}, 
"outputKeyPrefix" : "output2/test4/", 
"outputs" : [ { 
    "id" : "1", 
    "presetId" : "xxxxxxxxxxxx", 
    "key" : "xxxxxxxx", 
    "rotate" : "auto", 
    "status" : "Progressing" 
    } ] 
    } 

Я изменил значения. Я попытался разобрать его с помощью этого php-кода.

<?php 
$myFile = "file.log"; 
$lines = file($myFile); 
foreach ($lines as $no => $ln) { 
$out = explode(":", $ln); 
echo($out[1]); 
echo(trim($out[1])); 
?> 

Я получаю мой вывод как

{ { "PROGRESSING", "PROGRESSING", "2012-09-25", "2012-09-25", "xxxxxxxxxxxx", "xxxxxxxxxx", "xxxxxxxxxxxxxxx",

Он продолжает идти на .. не в правильном формате. Я хотел, чтобы это была пара ключевых значений. Как это сделать? Пожалуйста, ребята, нужна помощь! Мне также нужно получить их и сохранить в базе данных с помощью mysql.

+0

Это похоже на файл json. Используйте json-парсер – Jens

+0

попробуйте с помощью 'json_decode()' once. Я думаю, что это в формате json. –

+0

нет. его файл журнала задания перекодирования –

ответ

2

Update:

$logFile = file_get_contents('logfile.log'); 

// first we replace all instances of the string "Notification: " with a comma to separate the json objects 
$cleanLog = str_replace("Notification: ",",",$logFile); 

// next we replace the first comma 
$cleanLog = '[' . ltrim($cleanLog,",") . ']'; 

// construct the list of object 
$objects = json_decode($cleanLog); 

// use this main loop to iterate over all Notification rows 
foreach ($objects as $object){ 
    // write a mysql insert statement here, 
    // you can address each object and inner members as follows: 

    print $object->state . PHP_EOL; 
    print $object->outputKeyPrefix . PHP_EOL; 
    print $object->outputs[0]->id . PHP_EOL; 
    print $object->input->key . PHP_EOL; 
} 

с помощью этого файла журнала образца в качестве справки:

logfile.log

Notification: { 
"state" : "PROGRESSING", 
"version" : "2012-09-25", 
"jobId" : "xxxxxxxxx", 
"pipelineId" : "xxxxxxxxxxx", 
"input" : { 
    "key" : "upload2/xxxxx", 
    "frameRate" : "auto", 
    "resolution" : "auto", 
    "aspectRatio" : "auto", 
    "interlaced" : "auto", 
    "container" : "auto" 
}, 
"outputKeyPrefix" : "output2/test4/", 
"outputs" : [ { 
    "id" : "1", 
    "presetId" : "xxxxxxxxxxxx", 
    "key" : "xxxxxxxx", 
    "rotate" : "auto", 
    "status" : "Progressing" 
    } ] 
    } 
Notification: { 
"state" : "PROGRESSING", 
"version" : "2012-09-25", 
"jobId" : "xxxxxxxxx", 
"pipelineId" : "xxxxxxxxxxx", 
"input" : { 
    "key" : "upload2/xxxxx", 
    "frameRate" : "auto", 
    "resolution" : "auto", 
    "aspectRatio" : "auto", 
    "interlaced" : "auto", 
    "container" : "auto" 
}, 
"outputKeyPrefix" : "output2/test4/", 
"outputs" : [ { 
    "id" : "1", 
    "presetId" : "xxxxxxxxxxxx", 
    "key" : "xxxxxxxx", 
    "rotate" : "auto", 
    "status" : "Progressing" 
    } ] 
    } 
Notification: { 
"state" : "PROGRESSING", 
"version" : "2012-09-25", 
"jobId" : "xxxxxxxxx", 
"pipelineId" : "xxxxxxxxxxx", 
"input" : { 
    "key" : "upload2/xxxxx", 
    "frameRate" : "auto", 
    "resolution" : "auto", 
    "aspectRatio" : "auto", 
    "interlaced" : "auto", 
    "container" : "auto" 
}, 
"outputKeyPrefix" : "output2/test4/", 
"outputs" : [ { 
    "id" : "1", 
    "presetId" : "xxxxxxxxxxxx", 
    "key" : "xxxxxxxx", 
    "rotate" : "auto", 
    "status" : "Progressing" 
    } ] 
    } 

Строка после бита «Уведомление:» действительна json. Вы можете разобрать его следующим образом:

<?php 

$string = '{ 
"state" : "PROGRESSING", 
"version" : "2012-09-25", 
"jobId" : "xxxxxxxxx", 
"pipelineId" : "xxxxxxxxxxx", 
"input" : { 
    "key" : "upload2/xxxxx", 
    "frameRate" : "auto", 
    "resolution" : "auto", 
    "aspectRatio" : "auto", 
    "interlaced" : "auto", 
    "container" : "auto" 
}, 
"outputKeyPrefix" : "output2/test4/", 
"outputs" : [ { 
    "id" : "1", 
    "presetId" : "xxxxxxxxxxxx", 
    "key" : "xxxxxxxx", 
    "rotate" : "auto", 
    "status" : "Progressing" 
    } ] 
    }'; 

// construct object 
$object = json_decode($string); 

// call each property of the object or inner object 

print $object->state . PHP_EOL; 
// PROGRESSING 

print $object->outputKeyPrefix . PHP_EOL; 
// output2/test4/ 

print $object->outputs[0]->id . PHP_EOL; 
// 1 

// or, for multiple outputs 

foreach ($object->outputs as $output) 
    print $output->rotate . PHP_EOL; 
// auto 
+0

Код не работает, если я включаю файл с помощью file_get_contents ($ filename) –

+0

Я обновлю ответ с кодом для правильного анализа файла журнала –

+0

$ string не содержит «Уведомление». Строка не может быть отредактирована как ее выход из файла, который не нуждается в редактировании. –

0

Не вопрос, если ваша строка JSON не в JSON файл .. вы можете разобрать его ас-

<?php 
$myFile = "file.log"; 
$json = file_get_contents($myFile); 
$json= explode(":",$json,2); 
$json=$json[1]; 
$obj=json_decode($json,true); 
print_r($obj); 

?> 
+0

no выводится вывод. Это пусто –

+0

@ Reaching-Out, теперь это сработает для вас. –

+0

еще не показывает выход. Спасибо, но получил ответ :-) –

0

Попробуйте это:

$myFile = "file.log"; 
$str = file_get_contents($myFile); 
$json = trim(strstr($str, ':'), ': '); 
print_r(json_decode($json));// for Object 
print_r(json_decode($json, true));// for Array 

На самом деле «Уведомление» мешает строку будет прочитан в формате JSON. Поскольку действительный json должен начинаться с фигурных скобок или квадратных скобок, сначала удаляет «Уведомление», а затем обрезает лишние пробелы или двойную двоеточие с обеих сторон строки. Таким образом, остается только действительный JSON.

+0

Я не должен их снимать. Вот как я получаю свой файл. Я не должен входить и редактировать каждый раз. –

+0

Вам не нужно их удалять, этот код автоматически удалит их. Он отслеживает первое появление двойной кишки, а затем удаляет что-либо перед тем, что в этом случае является «уведомлением». –

+0

Не получился выход. Получил ответ. Спасибо. –

Смежные вопросы