json to php array conversion from REST service - php

I was getting a response from a REST flight api in JSON format which i was not able to convert into an array from JSON.
I have tried json encoding but it was only showing printing the json response but not converting it into array
Php Controller:
public function search_flites() {php controller
header('Content-type: application/json');
$this->load->library('curl');
$result = $this->curl->simple_get('http://13.235.39.41:8080/ettafly/api/session');
$Data = json_decode($result);
$session_id = $Data->SessionId;
$url = 'http://13.235.39.41:8080/ettafly/api/flightavaliblity';
$ch = curl_init($url);
$jsonData = array(
"user_id" => "Ettafly_APITest2019",
"user_password" => "Ettafly_TestPswd2019",
"access" => "Test",
"ip_address" => "13.235.39.41",
"session_id" => "$session_id",
"journey_type" => "OneWay",
"airport_from_code" => "DEL",
"airport_to_code" => "BOM",
"departure_date" => "2019-11-16",
"return_date" => "2019-11-18",
"adult_flight" => "1",
"child_flight" => "0",
"infant_flight" => "0",
"class_type" => "Economy",
"target" => "Test"
);
$ch = curl_init($url);
$jsonDataEncoded = json_encode($jsonData, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
$result2 = curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$Data2 = json_decode($result2, true);
}

You didn't send that request.
Check this out: https://www.php.net/manual/en/curl.examples.php#88055
<?php
public function search_flites() {
header('Content-type: application/json');
$this->load->library('curl');
$result = $this->curl->simple_get('http://13.235.39.41:8080/ettafly/api/session');
$Data = json_decode($result);
$session_id = $Data->SessionId;
$url = 'http://13.235.39.41:8080/ettafly/api/flightavaliblity';
$ch = curl_init($url);
$jsonData = array(
"user_id" => "Ettafly_APITest2019",
"user_password" => "Ettafly_TestPswd2019",
"access" => "Test",
"ip_address" => "13.235.39.41",
"session_id" => "$session_id",
"journey_type" => "OneWay",
"airport_from_code" => "DEL",
"airport_to_code" => "BOM",
"departure_date" => "2019-11-16",
"return_date" => "2019-11-18",
"adult_flight" => "1",
"child_flight" => "0",
"infant_flight" => "0",
"class_type" => "Economy",
"target" => "Test"
);
$ch = curl_init($url);
$jsonDataEncoded = json_encode($jsonData, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
$curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// You have to exec the curl request to get a response.
$result2 = curl_exec($ch);
$Data2 = json_decode($result2, true);
var_dump($Data2, JSON_PRETTY_PRINT);
}

by using below code
(
$payload = json_encode($jsonData);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$jsonData2 = json_decode($result, true);)
instead of
(
$jsonDataEncoded = json_encode($jsonData, JSON_PRETTY_PRINT);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
$curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// You have to exec the curl request to get a response.
$result2 = curl_exec($ch);
$Data2 = json_decode($result2, true);
var_dump($Data2, JSON_PRETTY_PRINT);)
Now i was able to conver the result into a array

Related

Posting JSON Data With PHP cURL returns Invalid Content Type error

I'm working with OpenSRS EMAIL API. I'm trying to create a new user email for a domain. In their first example, they are using JSON format :
{
"credentials": {
"user": "domain_admin#example.com",
"password": "sw0rdf1sh"
},
"user": "bhayden#example.com",
"attributes": {
"name": "Bob Hayden",
"password": "changeit",
"delivery_forward": true,
"forward_recipients": [
"bob.hayden#example.com
}
}
I'm sending this with cURL
$json = array(
"user" => $emailName,
"attributes" => array(
"name" => "Janet User",
"password" => $email_password,
"delivery_forward" => false
)
);
//
//
$payload = json_encode( $json );
//
$data = [
'Content-Type:application/json',
'X-Username:' . $connection_details['reseller_username'],
'X-Signature:' . md5(md5($payload . $connection_details['api_key']) . $connection_details['api_key']),
];
//
$ch = curl_init($connection_details['api_host_port']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
//
$response = curl_exec($ch);
//
//header('Content-type: application/json');
//
echo '<pre>';
echo $response;
echo '</pre>';
This print following error
0.9 400 0 Invalid Content-Type XCP
What am I doing wrong?
I fixed this issue by reformarting the entire request. This worked for me
$data = array(
"user" => $emailName,
"attributes" => array(
"name" => "Janet User",
"password" => $email_password,
"delivery_forward" => false
)
);
$postdata = json_encode($data);
//
$ch = curl_init($connection_details_email['api_host_port']);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$result = curl_exec($ch);
curl_close($ch);
print_r ($result);

Passing JSON data using CURL

I am using a CURL post to an existing API. The API returns the error content must be JSON or plain text. I json_encode data and post the encoded data to the API.
In the API, it says the Content-Type should be application/x-www-form-urlencoded'.
However, it still returns the error content must be JSON or plain text. What could be the issue with my code below after submitting my data in JSON format?
This is a sample request body in the API doc.
"item" : "Store",
"content" : {
"channel":"false",
"hop": "false",
"msg": "Order successfully placed."
}
Controller
public function postUrl()
{
$url = "https://api.com/";
$data = array("item" => "Nike Shoes","content" => array ("channel" => "false" ,"hop" => "false","msg" => "Item Sold"));
$postdata = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postdata);
}
Perhaps this is because boolean values are specified as strings.
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => false,
'hop' => false,
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}
Also try this
public function postUrl()
{
$url = 'https://api.com/';
$data = [
'item' => 'Nike Shoes',
'content' => [
'channel' => 'false',
'hop' => 'false',
'msg' => 'Item Sold'
]
];
$postData = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: text/json']);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$result = curl_exec($ch);
curl_close($ch);
Log::info($postData);
}

Adding OneSignal segments to filters array

I am using following PHP script to send OneSignal push notifications to subscribed devices.
<?PHP
function sendMessage(){
$content = array(
"en" => 'Testing Message desde el backend small icon '
);
$fields = array(
'app_id' => "xxxx",
'filters' => array(array("field" => "tag", "key" => "correo", "relation" => "=", "value" => "xxx")),
'data' => array("foo" => "bar"),
'small_icon' =>"ic_push",
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic xxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
print("\n\nJSON received:\n");
print($return);
print("\n");
?>
This script is working fine, and the notifications are sent.
Now I need to add more filters, for example I need to add a filter to two other segments that I have created at the OneSignal dashboard.
The segments are "skateboard" and "administrators".
How can I add these two segment to the filters array?
You need to pass segments name array in fields like you are passing tags.
$content = array(
"en" => 'Notification Message Here..'
);
$heading = array(
"en" => 'Heading goes here..'
);
$fields = array(
'app_id' => 'XXXXXXXXXXXXXXXXXXXXX',
'contents' => $content,
'headings' => $heading,
'included_segments' => array('SegmentName1','SegmentName2'),
'tags' = array(array("key" => "state", "relation" => "=", "value" => 'Delhi'))
);
$fields = json_encode($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8',
'Authorization: Basic XXXXXXXXXXXXXXXXXXX'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;

JSON API returning error although parameters are being sent

I'm sending a request to a JSON API system (http://help.solarwinds.com/backup/documentation/Content/service-management/json-api/login.htm) using PHP:
$base = 'https://cloudbackup.management/jsonapi';
$vars = array(
"jsonrpc" => "2.0",
"method" => "Login",
"params" => array(
"partner" => "partner",
"username" => "username",
"password" => "pass",
),
"id" => "1",
);
$ch = curl_init( $base );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
$output = json_decode($response, true);
But its returning this array in $output
Array
(
[error] => Array
(
[code] => -32700
[data] => 119
[message] => Parse error: Failed to parse request body: * Line 1, Column 1
'--------------------------' is not a number.
)
[id] => jsonrpc
[jsonrpc] => 2.0
)
I cannot work out why it's returning an error, because I'm sending the correct parameters that it says in the docs.
Can someone point me in the right direction or if I have missed something?
Set the content-type to application/json as curl is likely defaulting to sending it as x-www-form-urlencoded
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
also JSON-encode your array:
$jsonDataEncoded = json_encode($vars);
Full refactored sample:
$base = 'https://cloudbackup.management/jsonapi';
$vars = array(
"jsonrpc" => "2.0",
"method" => "Login",
"params" => array(
"partner" => "partner",
"username" => "username",
"password" => "pass",
),
"id" => "1",
);
$jsonDataEncoded = json_encode($jsonData);
$ch = curl_init( $base );
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
$response = curl_exec($ch);
curl_close($ch);
$output = json_decode($response, true);

Php Variable is null when i pass it to the array

I am trying to send user-specific web notifications with onesignal and i solved everything except this variable null problem.
I use that variable multiple times and there is no problem except these lines:
<?php
if(isset($_POST["sub"]))
{
$my_variable= $_POST["t1"];
$SQL = "some sql here";
if (mysqli_query($db, $SQL)) {
echo $my_variable;
echo "<br>";
function sendMessage(){
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => "$my_variable")),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage();
$return["allresponses"] = $response;
$return = json_encode( $return);
The result is :
1 JSON sent: {"app_id":"5b0eacfc-3ac8-4dc6-891b-xxxxx","filters":[{"field":"tag","key":"key","relation":"=","value":"null"}],"data":{"foo":"bar"},"contents":{"en":"test message"}}
I tried so many variations with/without quotas , json_encode() function but couldn't pass that variable to that array.
Your variable is out of scope.
You define $my_variable outside of the function sendMessage(), but proceed to try and use it within the function, without passing it as a parameter.
This can be fixed with the following:
function sendMessage($filterValue)
{
$content = array(
"en" => 'test message'
);
$fields = array(
'app_id' => "5b0eacfc-3ac8-4dc6-891b-xxxxx",
'filters' => array(array("field" => "tag", "key" => "key", "relation" => "=", "value" => $filterValue)),
'data' => array("foo" => "bar"),
'contents' => $content
);
$fields = json_encode($fields);
print("\nJSON sent:\n");
print($fields);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json; charset=utf-8', 'Authorization: Basic xxxxxxx'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
$response = curl_exec($ch);
curl_close($ch);
return $response;
}
$response = sendMessage($my_variable);
$return["allresponses"] = $response;
$return = json_encode( $return);

Categories