2016-03-24 129 views
-2

如何在PHP中顯示來自此JSON的屬性?我正在從包含多個JSON對象的文件中讀取JSON。我想打印並只顯示src_ip屬性。使用PHP顯示JSON對象屬性

PHP

json_string = file_get_contents("eve.json"); 

JSON

{ 
    "timestamp": "2016-03-24T20:41:16.751426", 
    "event_type": "alert", 
    "src_ip": "192.168.0.102", 
    "dest_ip": "192.168.0.105", 
    "proto": "ICMP", 
    "icmp_type": 8, 
    "icmp_code": 0, 
    "alert": 
    "action": "allowed", 
    "gid": 1, 
    "signature_id": 2100480, 
    "rev": 6, 
    "signature": "GPL ICMP_INFO PING speedera", 
    "category": "Misc activity", 
    "severity": 3 
} 
} 
+0

你如何看待它? –

+0

我想顯示它在PHP文件和WMN塊阻止SRC IP地址,並只顯示阻止的SRC IP地址數據 – ZaonX

+0

$ json_string = file_get_contents(「eve.json」); – ZaonX

回答

0

做象下面這樣:

$json_string = file_get_contents("eve.json"); 

$array = json_decode($json_string,true); 
print_r($array); //print array 

並獲得儘可能的src_ip值:

echo $array['src_ip']; 
+0

其不工作:( – ZaonX

+0

ZaonX

+0

它應該工作。請使用[jsonlint](http:// http://jsonlint.com/)驗證您的json。 –

1

JSON來客體;

<?php 
    //$json_string = file_get_contents("eve.json"); 
    $json ='{"timestamp":"2016-03-24T20:41:16.751426","event_type":"alert","src_ip":"192.168.0.102","dest_ip":"192.168.0.105","proto":"ICMP","icmp_type":8,"icmp_code":0,"alert":{"action":"allowed","gid":1,"signature_id":2100480,"rev":6,"signature":"GPL ICMP_INFO PING speedera","category":"Misc activity","severity":3}}'; 
    $obj = json_decode($json); 
    // print_r($obj); 

    echo $obj->src_ip; 
?> 

檢查結果:https://eval.in/541978

或JSON來陣列;

<?php 
    //$json_string = file_get_contents("eve.json"); 
    $json ='{"timestamp":"2016-03-24T20:41:16.751426","event_type":"alert","src_ip":"192.168.0.102","dest_ip":"192.168.0.105","proto":"ICMP","icmp_type":8,"icmp_code":0,"alert":{"action":"allowed","gid":1,"signature_id":2100480,"rev":6,"signature":"GPL ICMP_INFO PING speedera","category":"Misc activity","severity":3}}'; 
    $array = json_decode($json, true); 
    // print_r($array); 

    echo $array['src_ip']; 
?> 

檢查結果:https://eval.in/541976

+1

這不會給陣列中的響應如果你可以想要結果是數組傳遞'true'參數ter到json_decode並且你也使用了錯誤的json。 –

+0

是的,你是對的。我錯過了。 –

0

在PHP中有json_decode(),它以一個JSON字符串作爲參數,並以php數組的形式返回JSON對象:

<? 
    json_decode($json); 
?> 

其中$ json是一個包含json對象的字符串。 json_encode()是它的逆。