Parse data from webhooks - php

I am parsing data from webhook using this:
$data = json_decode(file_get_contents('php://input'), true);
So I have array of data in json file. How can I can get all of fields be as variables in json (Like { time: 'now' } be variable $time='now';

PHP has an extract function that will convert array keys into variables. Whether that is a good idea is a totally different question.

$data = json_decode(file_get_contents('php://input'), true)
return arrray expample array('time':'10:00');
you can get variable example
echo $data['time'];
oupt put => 10:00

Related

How to read json encoded value using php?

I have a variable in PHP, named as $partialSegments. I want to iterate through it and perform actions when I strike operator or rOperandValue, etc. I receive it in a function call, so while making the
function named(say):
public function convertJsCode($partialSegments){
//logic
}
I am struggling with the logic
"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}
Use json_decode() function in php
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed["segments"]["partialSegments"] as $val) {
$operator = $val["operator"]; // operator value
$rOperandValue = $val["rOperandValue"][0]; // rOperandValue value
}
?>
Step1: convert json encoded data into php array using json_decode(); function. This function receive two arguments: first one is: json_encoded data which should be decoded and 2nd one is: boolean(TRUE or FALSE). pass second argument as TRUE to convert the json concoded values as php array, if you pass false it will return php object.
Step2: iterate php array and set the logic like a charm.
<?php
$json = '{"segments":{"type":"custom","partialSegments":[{"type":"7","operator":11,"rOperandValue":["windows xp"],"prevLogicalOperator":null},{"type":"8","operator":11,"rOperandValue":["other"],"prevLogicalOperator":"AND"}]}}';
$parsed = json_decode($json, true);
foreach($parsed as $single){
$segments = $single['partialSegments'];
//print_r($single);
foreach($segments as $segment){
echo 'operator:'. $segment['operator'].'<br>';
print_r($segment['rOperandValue']);
// put your logic based on 'operator' or 'rOperandValue'
}
}
?>
Suggestion: Don't use hard code index to work with an array like: $segment['rOperandValue'][0]. array could be empty. i.e: if you want to do anything when a value is found in $segment['rOperandValue'] use in_array().

php: Extract value from array [duplicate]

I have an API that takes parameters from a post through JSON and I want to extract one of the values in an array for a key value pair. However, despite many attempts, I can't get it to work.
Here is my code:
$json = file_get_contents('php://input');
$request = json_decode($json, true);
$parameters = $request["result"]["parameters"];
When I log $parameters to a text file, it log as
{"numberofhits":"5"}
However, my efforts to capture the value 5 are not working:
$numhits = $json['numberofhits']; logs as empty.
So does:
$numhits = $parameters->numberofhits;
How can I capture the value 5 in a variable?
From your code above $json is a string and not a json object, your should use $request to access numberofhits
$request['numberofhits']
If your $parameters just shows {"numberofhits":"5"}, this means your post request just returned a json of a json. Try json decoding $parameters again like json_decode($parameters, true); and log that result. It should log the desired array.

php - convert mysql data into json object

I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code
public function json()
{
$content = $this->db->get('todolist'); //todolist table name
$data = $content->result_array();
echo json_encode($data);
}
Above code is converting database into JSON array.
Output
[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]
What will be best way to convert it into JSON object
Sangam try to understand the concept, check the following line:
$data = $content->result_array(); // $data is an array
echo json_encode($data); // here you are converting it into an json object
Your $data array contains more than one index in it that's why the json object is having multiple {} inside [];
You want to json_encode($data, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
Refer: PHP Array to Json Object
You can use JSON_FORCE_OBJECT see the example below.
echo json_encode($data, JSON_FORCE_OBJECT);
Assuming you're only getting one row back from your query.
change
echo json_encode($data);
to
echo json_encode($data[0]);

json_decode returns json string not an array

<?php
$json=file_get_contents('php://input',true);
$data = json_decode($json, true);
print_r($data);
?>
Output given is {"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"}
Json Data posted is:
{"EventTitle":"Game","EventBody":"body","EventDate":"20 November, 2016","EventType":"party"}
Writing the json data in a variable and passing it to json_decode works but posting the same from the "php://input" returns a JSON data instead of associative array.
It looks like #tkausl is correct. The JSON you're receiving has been double-encoded. Since it's double-encoded, a temporary solution would be to double-decode it.
$data = json_decode(json_decode($json), true);
But the real solution is to figure out why it's like that to begin with and fix it (if it's yours to fix).

GET info from external Array/API/URL using PHP

I have the url http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132 which leads to an array.
I want to get the value of the first 'sellorders' which in this case is: 0.00000048 and store it in the variable $sellorderprice.
Can anyone help?
Thanks.
Just access the url contents thru file_get_contents. Your page actually return a JSON string, to get those values into meaningful data, decode it thru json_decode, after that access the data needed accordingly:
$url = 'http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132';
$data = json_decode(file_get_contents($url), true);
$sellorderprice = $data['return']['DOGE']['sellorders'][0]['price'];
echo $sellorderprice;
That code actually points directly to index zero 0 which gets the first price. If you need to get all items an just simply echo them all you need to iterate all items thru foreach:
foreach($data['return']['DOGE']['sellorders'] as $sellorders) {
echo $sellorders['price'], '<br/>';
}
Its simple, you just have to decode json like this:
$json = file_get_contents("http://pubapi.cryptsy.com/api.php?method=singleorderdata&marketid=132");
$arr = json_decode($json, true);
$sellorderprice = $arr['return']['DOGE']['sellorders'][0]['price'];

Categories