PHP : How to send data as a JSON object - php

I have build a simple PHP API system.
Now a partner company (* that isn't quite behaving as a partner *) and they are sending us data but since their system is making a lot of requests we need to debug.
The debug data they send us are the following:
But I have no clue might sound stupid but unfortunately yes. How to send this to our system as a JSON object.
Could anyone tell me how I can send this data as a JSON object so I can see how our system responds?
{"requested_info":"pers_code_live","provider_id":"20","provider_group_id":"4","indoor":false,"provider_location":"buiten","StartDate":"14-10-2016 16:00","EndDate":"22-10-2016 23:30","email":null,"lang":"nl","personal_code":"wehavediscount"}
Thanks in advance
EDIT
The info I receive is only readable by :
$JSonData = json_decode(file_get_contents('php://input'), true);
But I have no idea how to send the above mentioned data in a format that I have accept in the manner as described two lines up.
I can create a post variable with a JSON encoded array. That's no biggie. But the problem is the JSon object. I don't know how to send something as a JSon object and re-create their created situation.

The standard way is with json_encode():
$arr = ["first key" => 1, "second key" => "two", "third => [1,2,3]];
echo json_encode($arr);
Which will return
{"first key": 1, "second key": "two", "third": {1,2,3}}

Related

how to identify the code which is receiving by my website

i make one php script who send the data one api after successful submission it will reply with all codes which i dont know how to read it. i make one php script who send the data one api after successful submission it will reply with all codes which i dont know how to read it.
{
"ErrorCode": "000",
"ErrorMessage": "Success",
"JobId": "b770e8c9-118b-4347-9708-fcd1176c51d7",
"MessageData": [
{
"Number": "918237020012",
"MessageParts": [
{
"MsgId": "918237020012-9be10ca3793b4e7c83c74d3dfbbfd60d",
"PartId": 1,
"Text": "testing completed"
}
]
}
]
}
This "codes" is called Json Object and in your case it's string encoded so you can decode it into a PHP object something like:
$obj = json_decode($response);
and you can access it's attributes like this:
echo $obj->JobId;
furthermore you can refer to the PHP documentation json_decode
They are called JSON Strings. It's a lightweight data-interchange format.
To decode the JSON string in PHP use json_decode. Like this,
$json_object=json_decode($jsonString);
It will return you PHP Object by default and you just need to read the Object properties. Like this,
echo $json_object->json_key;

Getting Instagram subscription JSON data from post in PHP

This whole process of subscriptions for the Instagram API seems to be less than straight forward.
I have some code set up to receive the post data sent when Instagram hits me with a notification of a post from one of my subscriptions. However when I try to view the data, the raw JSON, it posts I can't get at it. If I print_r or var_dump I just get the number 1.
See my code for accessing the data:
// Catches realtime updates from Instagram
if ($_SERVER['REQUEST_METHOD']==='POST') {
// Retrieves the POST data from Instagram
$update = file_get_contents('php://input');
$data = json_decode($update);
var_dump($data); //Outputs 1
print_r($data[0]); //Outputs 1
}
How can I get at the JSON as an array?
This is what the JSON should look like:
[
{
"subscription_id": "1",
"object": "user",
"object_id": "1234",
"changed_aspect": "media",
"time": 1297286541
},
{
"subscription_id": "2",
"object": "tag",
"object_id": "nofilter",
"changed_aspect": "media",
"time": 1297286541
},
...
]
Thanks for any help.
Update 1
I've used PHP to print the HTTP headers. There's content because it show's it's length. Still unable to get at it though. This rules out it being an Instagram issue, I think
If you are using PHP, I guess the simplest way to access input data is using $_GET and $_POST superglobals. In this case, try to var_dump($_POST) and see what you get.
If you get some content from $_POST, you can use json_decode to decode JSON into an array.
You can also try some PHP implementations of the Instagram API, like this one: https://github.com/macuenca/Instagram-PHP-API It will to the work you need.
Woop found the problem and solved it. It's not easy to debug because all of this happens when Instagram hit your page so you don't really see the output.
What I needed to do was create a foreach loop to run through the decoded JSON. After a lot of debugging and head scratching the JSON isn't empty, it just starts with a JSON array.
Anyway here's the code now that works:
// Catches realtime updates from Instagram
if ($_SERVER['REQUEST_METHOD']==='POST') {
// Retrieves the POST data from Instagram
$update = file_get_contents('php://input');
$data = json_decode($update);
foreach($data as $k => $v) // can be multiple updates per call
{
$sub_id = $v->subscription_id; //Contains the JSON values
$user = $v->object_id;
}
}
If you want to see the outputs from $sub_id for example I suggest logging them or email them to yourself for example.

Send request to api website and then api give me some data in array format, how to work with this data?

Send request to api website and then api give me some data in array format, how to work with this data ?
When I access to: example.com/api.php?name=papaya, it's will show
Array ( [0] => papaya [1] => fruit )
in my site, I want to work with this array data like
$url = "example.com/api.php?name=papaya ";
if ($url[1] == "fruit" )
{ echo "food"; }
How to do that?
You guys aren't understanding what the OP is asking. He's asking how he can use the data that is returned from the api request. I don't think he has access to the API itself but rather the end-point.
Now to answer the question.
Basically you'd need to either use cURL or something like file_get_contents().
For this example, I'm going to use file_get_contents() to give you a basic idea:
Now the below example will get the returned data from the geoplugin.net api.
$ip = $_SERVER['REMOTE_ADDR'];
$result = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
print_r($result);
?>
For your case, you'd do something similar:
<?php
$result = #json_decode(file_get_contents("example.com/api.php?name=papaya"));
// do what you need to with result...
echo $result[0];
?>
Obviously this isn't the best way to do it; as you'd need to make sure there were no errors (suppressed the errors with the # before the json_decode()).
Now I'm not going spoon feed you, so here are some examples on how to do some cURL requests.
PHP.NET cURL Examples
Simple PHP cURL Example
All examples of PHP cURL....
If you have control over the API, then set the response header Content-Type: application/json, then json_encode any output, and json_decode on the client side.
Otherwise theres not much you can do with that string.. possibly use a regex method to extract the key and values?

"JSON text must be an object or array" error

I'm using PHP to connect to an API and register some info using JSON and HTTP POST but it is not going well.
That is what I do:
I create a JSON object with the json_encode function:
$name = 'Mike';
$surname = 'Hans';
$fields = array('name' => json_encode($name), 'surname' => json_encode($surname));
$postData = json_encode($flds);
Once i have the post data, I just connect to the API with curl and login with oauth, but the API responde says:
JSON text must be an object or array (but found number, string, true,
false or null, use allow_nonref to allow this)
I have checked the allow_nonref in Google, but i could not find anything for PHP, all I have found is for Perl. Does anyone have any solution/advice to solve this?
Thanks!
You probably need to send the entire POST as JSON without nesting calls to json_encode, like this:
$fields = array('name' => $name, 'surname' => $surname);
$postData = json_encode( $fields);
To follow up on #nickb's answer, please only use one call to json_encode, it's far better at constructing valid json that you and I are, and it's more efficient to boot! (though we are entering the realm of micro-optimisation).
Have you tried taking the output of the json_encode and putting it into a validator/formatter such as the one here : http://jsonviewer.stack.hu/
Also, I think another likely problem could be the headers you are sending? The recieiving server could be strict and enforce that you use the correct 'Content-Type'. Are there any API docs avaliable?

Codeigniter and PHP. Using POST to access array

I am building an API using Codeigniter and Phils RESTserver and I am trying to send an array to the API using a POST request.
When I POST this:
query=("email#example.com","anna#nicole.com")
I can access it like this:
$this->post('query');
This produces:
("email#example.com","anna#nicole.com")
How can I loop through these email addresses in PHP?
Do anyone got another idea?
Thankful for all input!
If you are controlling the POST request, then you should POST an array to PHP, not a delimited list, which will automatically create an array that is available for use when the server receives the request. This is what J0HN means when he says use square brackets instead of parenthesis.
However, it depends on how you're sending the request to the server to determine the proper way to send an array to PHP. You might need:
query=["one#example.com", "two#example.com"]
query[]=["one#example.com", "two#example.com"]
Or other variants...
Since you don't elaborate on how you're making the request to the server, the proper way to POST an array cannot be determined.
On the other hand, if you can't POST an array for some reason, you can always send a JSON-encoded string and easily decode it:
// Assuming $this->post('query') = json_encode( array( "one#example.com", "two#example.com"));
$emails = json_decode( $this->post('query')); // Array of emails

Categories