Retrieve all IDs using PHP from a structured log string - php

I need to somehow handle the following recursive log output using PHP, creating an array or encoding it in json, the ultimate goal is to retrieve the "id" value of each getusers section, i've done some tests but i can't get a good result.
This is just a portion of the log string containing all the getusers sections(there can be thousands):
getusers: {
"user": {
"id": 1569976517,
"type": "user",
"first_name": "Mike",
"username": "MikesNick",
"verified": false,
"restricted": false,
"status": {
"_": "userStatusRecently"
},
"access_hash": -7018287513210933137,
"bot_nochats": false
},
"date": 1613450429,
"role": "user"
}
getusers: {
"user": {
"id": 717418136,
"type": "user",
"first_name": "John",
"last_name": "Smith",
"username": "JhonsNick",
"verified": false,
"restricted": false,
"status": {
"_": "userStatusOffline",
"was_online": 1613230815
},
"access_hash": 1814429223003924316,
"bot_nochats": false
},
"date": 1613245788,
"role": "user"
}
What is the best way to manage it and recover the data I need?

I found a way to extract the IDs from the log using the following code
$exploded = explode("getusers:",$logString);
foreach($exploded as $group){
$decoded = json_decode($group,true);
echo $decoded["user"]["id"]."<br/>";
}

Related

I want to make two tables nested objects in Laravel controller

I have two tables. One is the ability table and the other is the user table. I want to output these tables in a similar way to the following.
{
"id": 1,
"fullName": "John Doe",
"username": "johndoe",
"avatar": "/img/13-small.d796bffd.png",
"email": "admin#demo.com",
"ability": [
{
"action": "manage",
"subject": "all"
}
],
}
But I get these
[
{
"id": 1,
"name": "Admin",
"email": "admin#admin.com",
"role": "Admin",
"telefon": "05355141450",
"password": "$2y$10$bigkDO75WWzeBCk60ZT/3eUvXlOKRocpYzWoTlhFhbSuft1ojdWDW",
"status": "1"
}
]
and
{
"ability": [
{
"id": 1,
"action": "manage",
"user_id": "1",
"subject": "all"
}
]
}
I use Laravel as framework. I'm pulling data with Query. But I couldn't do these two together. Can you please help?

PHP - Retrieve JSON data and values [duplicate]

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm new into PHP and JSON and I have a problem, I want to retrieve a item and value from a JSON:
{
"status": true,
"webhook_type": 100,
"data": {
"product": {
"id": "lSEADIQ",
"attachment_id": null,
"title": "Registration",
"description": null,
"image": null,
"unlisted": false,
"type": "service",
"price": 1,
"currency": "EUR",
"email": {
"enabled": false
},
"stock_warning": 0,
"quantity": {
"min": 1,
"max": 1
},
"confirmations": 1,
"custom_fields": [
{
"name": "Forum username",
"type": "text",
"required": true
}
],
"gateways": [
"Bitcoin"
],
"webhook_urls": [],
"dynamic_url": "",
"position": null,
"created_at": "2018-10-01 12:51:12",
"updated_at": "2018-10-01 12:55:46",
"stock": 9223372036854776000,
"accounts": []
},
"order": {
"id": "8e23b496-121a-4dc6-8ec4-c45835680db2",
"created_at": "Tue, 02 Oct 2018 00:54:56 +0200",
"paid_at": null,
"transaction_id": null,
"confirmations": 1,
"required_confirmations": 3,
"received_amount": 0,
"crypto_address": "1NeNQws7JLbTr6bjekfeaXSV7XiyRsv7V8",
"crypto_amount": "0.4815",
"quantity": 1,
"price": 19.99,
"currency": "EUR",
"exchange_rate": "1.21",
"gateway": "BTC",
"email": "webhook#site.gg",
"ip_address": "123.456.789.111",
"agent": {
"geo": {
"ip": "214.44.18.6",
"iso_code": "US",
"country": "United States"
},
"data": {
"is_mobile": false,
"is_table": false,
"is_desktop": true,
"browser": {
"name": "Chrome",
"version": "63.0.3239.132"
}
}
},
"custom_fields": [
{
"name": "user_id",
"value": 184191
}
],
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3)"
}
}
}
I want to retrieve items from data -> order, for example "id" or "ip_address".
Thank you for read this, I hope someone can help me in this, because I'm lost, I started to code very recently and I'm trying to learn a lot.
Regards!
Where test.json is the json you uploaded, place it in a file named test.json and ensure its placed in the same directory.
<?php
$load = file_get_contents("test.json") or die("JSON load failed");
$json_a = json_decode($load, true);
print $json_a['data']['order']['ip_address'] . "\n";
?>
Gives:
123.456.789.111
My answer reads the JSON from a file as were it dumped directly in your code, which indeed it could be, it would make the code less readable and your file more messy.
If you dont want to place the file in the same directory, simply specify the full file path. E.g. file_get_contents("this/dir/here/test.json");
You can read about how json_decode works here, its essential we pass it the true parameter to make our arrays associative.
You can extract your need array from JSON data. You can use a loop too to read all your data inside the order array.
$array = json_decode($json, true);
$verbose = $array['data'];
$orderArray = $verbose['order'];
print_r($orderArray);
echo $orderArray['id'];
echo $orderArray['ip_address'];

How to read context parameters using php webhook in dialogflow

Need help with the following I writing a webhook in php, and need the ability to read the context parameters.
Can someone help me to understand how it can be done?
Here is my example JSON:
{
"id": "6e774dc2-2323-42b3-bd3c-ab64930f8b92",
"timestamp": "2017-12-22T21:12:19.094Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "Yes",
"action": "Triage.Triage-yes",
"actionIncomplete": false,
"parameters": {},
"contexts": [
{
"name": "triage-followup",
"parameters": {
"triagecriteria": [],
"roomEntity.original": "",
"roomname": "300",
"roomnames.original": "living",
"roomid": "200",
"context": "",
"roomnames": [
"living"
],
"counter": "400",
"roomEntity": "100",
"triagecriteria.original": ""
},
"lifespan": 3
}
],
"metadata": {
"intentId": "ecd4a2e5-65a0-41b2-ac72-edcf4d2e73f2",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 203,
"intentName": "Triage - yes"
},
"fulfillment": {
"speech": "Yes",
"source": "agent",
"displayText": "No",
"messages": [
{
"type": 0,
"speech": "Yes"
}
]
},
"score": 1
},
"status": {
"code": 200,
"errorType": "success",
"webhookTimedOut": false
},
"sessionId": "db8c1a4e-fa0c-4257-a536-78b63879eef9"
}
I want to be able to refer to [results][Contexts][Parameters]
I am using
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true, 512, JSON_BIGINT_AS_STRING);
and trying to access the value as $update["results"]["Contexts"]["Parameters"]["roomid"]
The names are case sensitive, and you need to be careful about trailing "s"es. Since some of the items are numerically indexed arrays, you'll need to include that as part of the index. Try
$update["result"]["contexts"][0]["parameters"]["roomid"]

Parse this JSON OBJECT in PHP

I am going to be receiving a JSON object via HTTP POST and I am finding it difficult to parse it. This is what the JSON object looks like:
{ login: {username: 123, password: 456} }, questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]}
I want to parse it into 3 different variables $username, $password and $q
From the example, this is what I expect it to be:
echo $username // **output:** 123
echo $password // **output:** 456
echo $q //**output:** questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]
First your example is not a valid json. Here the valid one:
[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]
Next you can use json_decode from a string:
$x = '[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]';
$q = json_decode($x);
print_r($q);
echo $q[0]->login->username;
The JSON in the example is invalid, I fixed it and put together a test, I think this is what you're looking for.
<?php
$json = <<<JSON
{
"login": {
"username": 123,
"password": 456
},
"questions": [
{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
},
{
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}
]
}
JSON;
$decoded = json_decode($json);
$username = $decoded->login->username;
$password = $decoded->login->password;
// Re-encode questions to a JSON string
$q = json_encode($decoded->questions);
echo $username."\n";
echo $password."\n";
echo $q."\n";

Processing JSON retrieved with curl

I am using curl function to get the data from gotowebinar url. here is the code
$data=curl_exec($curl);
#curl_close($curl);
$newdata=json_decode($data, true);
print_r($newdata);
I am getting this output:
[
{
"registrantKey": 12345,
"firstName": "xxx",
"lastName": "xxx",
"email": "xxx#yahoo.com",
"status": "WAITING",
"registrationDate": "2012-07-11T16:54:11Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/New_York"
},
{
"registrantKey": 12345,
"firstName": "xxx",
"lastName": "xxx",
"email": "xxx#yahoo.com",
"status": "WAITING",
"registrationDate": "2012-07-05T23:55:23Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/New_York"
},
{
"registrantKey": 12345,
"firstName": "xxx",
"lastName": "xxx",
"email": "xxx#yahoo.com",
"status": "WAITING",
"registrationDate": "2012-07-11T23:27:56Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/Chicago"
},
{
"registrantKey": 12345,
"firstName": "xxx",
"lastName": "xxx",
"email": "xxx#visioninvesting.com",
"status": "WAITING",
"registrationDate": "2012-07-11T23:29:40Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/Chicago"
},
{
"registrantKey": 12345,
"firstName": "xxx",
"lastName": "xxx",
"email": "xxx#yahoo.com",
"status": "WAITING",
"registrationDate": "2012-07-11T18:14:32Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/Chicago"
},
{
"registrantKey": 12345,
"firstName": "test",
"lastName": "1",
"email": "xxx#yahoo.com",
"status": "WAITING",
"registrationDate": "2012-06-29T21:07:10Z",
"joinUrl": "https://www1.gotomeeting.com/join/123/456",
"timeZone": "America/Denver"
}
]
I used json_decode to format the data but it did not work. I want to format the output so that I can use its values in program.
Here is some simple PHP code for looping over the resulting object from calling json_decode.
$newdata = json_decode($data);
foreach($newdata as $entry) {
echo "{$entry->firstName} is {$entry->status}. " .
"Their key is {$entry->registrantKey}.<br />\n";
}
You can access any of the properties you see in the returned json from the decoded object.
Since you get an array of objects, you can loop over each entry (as shown above), or access a specific entry like this:
$third = $newdata[2]->firstName;
Hope that helps get you started.
Try converting it to an array first:
$newdata = (array) json_decode($data, true);

Categories