Foreach with this type of JSON (PHP)

Asked

Viewed 548 times

1

I am trying to display the values of a JSON with PHP more unsuccessfully. Code Used:

JSON:

{
    "event_name": "offline_message",
    "widget_id": "sEcXk3TXEw",
    "visitor": {
        "name": "ARTULITO BARBOSA DE SOUSA",
        "email": "[email protected]",
        "phone": "11-952896992",
        "number": 15070,
        "chats_count": 1
    },
    "offline_message_id": 767,
    "message": "<Message text is not displayed here>",
    "session": {
        "geoip": {
            "region_code": "27",
            "country_code": "BR",
            "country": "Brazil",
            "region": "Sao Paulo",
            "city": "São Paulo",
            "isp": "",
            "latitude": "-23.4733",
            "longitude": "-46.6658",
            "organization": "NET Virtua"
        },
        "utm": null,
        "ip_addr": "201.6.231.89",
        "user_agent": "Mozilla\/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/58.0.3029.110 Safari\/537.36"
    }
}

I only need to get the data from the fields:

  • event_name

  • Visitor->name

  • Visitor->email

  • Visitor->phone

  • Session->geoip->Region

  • Session->geoip->city

  • Session->geoip->latitude

  • Session->geoip-> longitude


I was trying something in PHP that looked like this

<?php

$url = 'https://admin.jivosite.com/widgets/webhooks-log/721441/1';
$content = file_get_contents($url);
$json = json_decode($content, TRUE);

foreach($json['visitor'] as $item) {
    print $item['name'][0];

}

?>

The link to the entire list I’m trying to read: https://admin.jivosite.com/widgets/webhooks-log/721441/1

  • Have you checked in $content is getting the JSON data correctly? Because apparently the indicated page requires authentication and with only the function file_get_contents you cannot do this authentication.

1 answer

0

json_decode in this case will return only associative arrays because all json is keyed { There is in json the bracket [. In this case you won’t find an element with index 0 in any json node.

event_name vai ser $json['event_name']
visitor->name vai ser $json['visitor']['name ']
...
session->geoip->region vai ser $json['session']['geoip']['region']
...
  • So if I received this via post (webhooks) would it look like this?! $request = file_get_contents("php://input");&#xA;$output = json_decode($request, true);&#xA;$name = $output['visitor']['name'];&#xA;$email = $output['visitor']['email'];&#xA;$phone = $output['visitor']['phone'];&#xA;$city = $output['session']['geoip']['city'];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.