How do i get a data from JSON server response in PHP - php

I'm sending a JSON request in PHP and i get a response from the server, that looks like this:
{"success":true,"result":
{"items":
[{"woj":"łódzkie","powiat":"kutnowski","gmina":"Bedlno","kod":"99-
311","miasto":"Adamów","id":"99-311Adamów167271172700"}]},
"error":null,
"unAuthorizedRequest":false}
I want to pick a content from "woj" and "powiat" but it doesn't work.
My code looks like this:
$code = 'https://hetman.e4b.com.pl/api/services/app/kodPoczt/KodPocztInfo?
kod='.$kod;
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $code);
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//execute post
$result1 = curl_exec($ch);
//close connection
curl_close($ch);
echo $result1;
$wynik = json_decode($result1, true);
echo $wynik['result'][0]['woj'];

show your full code... curl isnt inited in your example and return_transfer isnt set. whats the output of $result1?
anyway its
$wynik['result']['items'][0]['woj'];

$temp = '{
"success": true,
"result": {
"items": [{
"woj": "łódzkie",
"powiat": "kutnowski",
"gmina": "Bedlno",
"kod": "99-311",
"miasto": "Adamów",
"id": "99-311Adamów167271172700"
}]
},
"error": null,
"unAuthorizedRequest": false
}';
$result = json_decode($temp,true);
echo $result['result']['items'][0]['woj'];

Related

How do I get this PHP cURL Get working for this URL

I have this URL as a GET
https://api-gametroove.eeposit.com/auth/gameland_subscription_status/
Need to send it like this
https://api-gametroove.eeposit.com/auth/gameland_subscription_status/270830000000
with 270830000000 being the mobile number.
The response is supposed to be
{
"success": true,
"message": "Subscription status checked successfully.",
"params": {
"subscriptStatus": true
}
}
I am using the following code, but don't get any response back.
function subscriber($msisdn){
$URL = "https://api-gametroove.eeposit.com/auth/gameland_subscription_status/".$msisdn;
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$URL);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$output=curl_exec($ch);
curl_close($ch);
echo $output;
}
subscriber('2773000000');
If I do above nothing is returned. How can I check if any errors or should I use another
method to do the GET for thsi URL?

PHP while loop curl_exec

I am working on creating div for each result coming from curl_exec json GET request. I have tried the code below using cURL in PHP. When I run this code nothing comes from the foreach.
//API Url
$url = 'https://api.clover.com:443/v3/merchants/'.$merchantid.'/categories/';
//Initiate cURL.
$ch = curl_init($url);
$headers = array(
'Content-type: application/json',
'Authorization: Bearer '.$authtoken.' ',
);
//Tell cURL that we want to send a GET request.
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
//Execute the request
$resp = curl_exec($ch);
$respArray = json_decode($resp, true);
foreach($respArray as $key => $value) {
echo $key . " : " . $value;
}
curl_close($ch);
This returns the following:
{
"elements": [
{
"id": "QWS8MSMAT49E6",
"name": "Other",
"sortOrder": 2
},
{
"id": "35K000MJVVFHE",
"name": "Pizza",
"sortOrder": 1
}
],
"href": "http://api.clover.com/v3/merchants/{[MID]}/categories?limit=100"
}
I'm trying to get the information above into a div, for example:
think it works like this:
$data = json_decode($resp);
foreach($data->elements as $element) {
echo '<div id="group_'.$element->id.'" class="product_group">'.$element->name.'</div>';
}
I have resolved the issue with adding
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
To the code. As has been explained Here (by Mihai)
"By default curl_exec outputs the data it gets from the server to the
standard output so your $response variable doesn't really have the
actual response data in it. If you want to get the data in a variable
set the CURLOPT_RETURNTRANSFER option before calling curl_exec."
And Martin Zeitler's Answer was right with removing true from json_decode()

Extra garbage values added when posting JSON data using cURL

I am trying to create an API using cURL & JSON.
Now In my first PHP file I am sending data as JSON data, Like below:
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
But on my SERVER where I get this request when I show (using var_export()) the values:
public function login()
{
$client_data = $this->input->post();
var_export($client_data);
}
Error:
array ( '"{\u201cRequest\u201d:\u201cLogin\u201d,\u201cUsername\u201d:\u201cBIZRTC\u201d,\u201cAPIAccessKey\u201d:\u201cAW342FFGRTR56RTH\u201d,\u201cGMT-Timestamp\u201d:_\u201c1489670000\u201d}"' => '', 0 => '', )
Even if I decode it there I still get \u. Also I dont understand how are these values appended : at starting : '"{\\u201c and this \\u201d}"' => '', 0 => '', at the back.
What are these values?
How do I decode this JSON?
Am I Posting right data to Server?
Updated code
Client.php
public function index()
{
$url = 'http://172.24.130.50/testbiz/server/login';
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
//execute post
$result = curl_exec($ch);
echo "<pre>".$result."</pre>";
//close connection
curl_close($ch);
}
Server.php
public function login()
{
var_export($_POST);
}
You need to give array in json_encode, Instead of string.
Replace:
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
To:
$field_string= '{
"Request": "Login",
"Username": "anonymous",
"APIAccessKey": "AW342FFGRTR56RTH",
"GMT-Timestamp": "1489670000"
}';
Problems in code:
Incorrect json.
Invalid quotes(”) in json.
Passing string in json_encode.
if you are storing json string in variable then you don't need the json_encode() because it is used to convert array to json string.
$field_string = '{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}';
$json = $field_string;
//open connection
$ch = curl_init();
//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($json))
);
it is because of below line
$field_string = "{“Request”: “Login”, “Username”: anonymous, “APIAccessKey”: “AW342FFGRTR56RTH”, “GMT-Timestamp”: “1489670000”}";
$json = json_encode($field_string);
suppose to be like this
$field_string = array("reqest"=>"login", "user_name"=> "anonymous", "API_AccessKey"=> "AW342FFGRTR56RTH", "GMT_Timestamp"=> "1489670000");
$json = json_encode($field_string);

XBMC api get request in php with curl

I'm trying to do a GET request to the XBMC api in PHP, but i cant get it to work. I already have a valid url, thats working when i simulate a GET request with a REST client.
http://localhost:8085/jsonrpc?request={"jsonrpc": "2.0", "id": 1, "method": "Input.ExecuteAction", "params": {"action":"left"}}
I get a parse error from xbmc when i simulate a POST:
{
"error": {
"code": -32700,
"message": "Parse error."
},
"id": null,
"jsonrpc": "2.0"
}
This is the code i currently have:
<?php
$jsonString = "{\"jsonrpc\": \"2.0\", \"id\": 1, \"method\": \"Input.ExecuteAction\", \"params\": {\"action\":\"left\"}}";
$url = "http://localhost:8085/jsonrpc?request=".$jsonString;
get($url);
function get($url){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 7);
$result = curl_exec($ch);
print $result;
curl_close($ch);
}
But this wont do the job, just like when i simulate a POST request a parse error is returned.
So my thoughts are that i'm doing a POST request, am i?
If no, what would be the problem then?
I just ran into the same problem.
You need to encode the url you are using for XBMC (Kodi nowadays). So in your case:
$jsonString
should be replaced by
urlencode($jsonString)

Edit json response from curl response

<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=xxxxx&callback=angular.callbacks._0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);
$jsonString = json_encode($response, true);
$data=json_decode($jsonString);
echo '<pre>',print_r($data),'</pre>';
$status = curl_getinfo($curl);
curl_close($curl);
The output is:
angular.callbacks._0({
"disclaimer": "xx",
"license": "xx",
"timestamp": 1368136869,
"base": "USD",
"rates": {
"AED": 3.672819,
"AFN": 53.209,
"ALL": 107.953875,
"AOA": 96.358934,
"ARS": 5.214887,
....
"XOF": 501.659003,
"XPF": 91.114876,
"ZMK": 5227.108333,
"ZMW": 5.314783,
"ZWL": 322.387247
}
})
But i need to edit this output to this one (only with three rates (AED/AFN/AOA)). So, basically edit the json response in the section of rates. How can i do that?
angular.callbacks._0({
"disclaimer": "xx",
"license": "xx",
"timestamp": 1368136869,
"base": "USD",
"rates": {
"AED": 3.672819,
"AFN": 53.209,
"AOA": 107.953875,
}
})
The $response is not in correct json format:
You must remove the unnecessary parts from it:
$jsonString= substr($response, 21, -1);
You can do:
<?php
$json_url = "http://openexchangerates.org/api/latest.json?app_id=5bf388eb6f7e40209b9418e6be44f04b&callback=angular.callbacks._0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $json_url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
$response = curl_exec($curl);
$jsonString= substr($response, 21, -1);
$data=json_decode($jsonString, true);
// Get the list of rates
$rates = $data['rates'];
$new_rates = array();
$new_rates['AED'] = $rates['AED'];
$new_rates['AFN'] = $rates['AFN'];
$new_rates['AOA'] = $rates['AOA'];
$data['rates'] = $new_rates;
echo 'angular.callbacks._0('.json_encode($data).')';
$status = curl_getinfo($curl);
curl_close($curl);
It's returning a response for jsonp. You would need that on the client side, but not the server. You might try:
http://openexchangerates.org/api/latest.json?app_id=xxxxx
(i.e. omit the callback). Otherwise take a look at their API to see if you can format the request differently to receive pure JSON back without the callback.
If you absolutely can't, then you can just strip off the bad parts:
preg_match('/{.*}/', $response, $matches);
$json = json_decode($matches[0]);
Once you have the valid JSON, it's a simple matter of unsetting:
unset($json->rates->XOF);
//etc.
You could also just write the content you need to some other object if it's easier.
You may want to take a look at the API to see if you can get only specific rates back.
Read the JSON string into a PHP mapping array with json_decode, pick only the elements you need, compose a new array with them and finally reserialize it with json_encode.
Note: this method is more robust than a regex/string based one, as it makes sense of what it's being processed, thus allowing for mutation in the structure of the JSON, as long as the elements you need are at their places.
For selecting elements, use:
$keep = array("AED", "AFN", "AOA");
$data["rates"] = array_intersect_key($data["rates"], array_flip($keep));

Categories