json_decode() returns NULL - php

I call web services to fetch some data.The code is below
header('Content-Type: application/json; charset=windows-1253');
//$jsonobj = '{"Peter":35,"Ben":37,"Joe":43}';
//$jsonData ='{service:login,username:demo,password:demo,appid:256}';
$jsonData = array(
'service' => 'login',
'username' => 'demo',
'password' => 'demo',
'appid' => '256'
);
//API Url
$url = 'http://myservice/s2services';
//Encode the array into JSON.
$postdata = json_encode($jsonData);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_ENCODING , "gzip");
$output = curl_exec($ch);
$result_array = json_decode($output, true);
var_dump($output);
The problem is when i try to decode json object.When i try this with this line of code $result_array = json_decode($output, true); returns NULL
Output from curl_exec below
string(514) "{"success": true, "clientID":"9J8pHsHKOKzgR59M9JL2RLLKULb3I6WbDKCbDZ1KLNbLGN94OqbOJLHLH4XsHIKtGcnLLYKtGYKtH7LLSNb5LYKtGoKrGt9EKoKrH5KbDKDGGKHKSb55", "objs":[{"COMPANY" : "1000","COMPANYNAME" : "Company Demo ΑΕ","BRANCH" : "1000","BRANCHNAME" : "Athens","MODULE" : "13","MODULENAME" : "Customer","REFID" : "47","REFIDNAME" : "Design ","USERID" : "1","FINALDATE" : "","ROLES" : "","XSECURITY" : "0","EXPTIME" : ""}], "ver":"5.00.520.11321", "sn":"01100313514211", "off":false, "pin":false, "appid":"256"}"
Where is the problem here with my code ?
Thanks for any help

Related

GA4 custom event from server side, can someone tell me how i can do the following code in php?

const measurement_id = `G-XXXXXXXXXX`;
const api_secret = `<secret_value>`;
fetch(`https://www.google-analytics.com/mp/collect?measurement_id=${measurement_id}&`api_secret`=${api_secret}`, {
method: "POST",
body: JSON.stringify({
client_id: 'XXXXXXXXXX.YYYYYYYYYY',
events: [{
name: 'tutorial_begin',
params: {},
}]
})
});
can someone tell me how i can do the above code in php?
i have tried the following but it is not working,
$data = array(
'client_id' => self::ga_extract_cid_from_cookies(),
'user_id' => 123,
'timestamp_micros' => time(),
'non_perosnalised_ads' => false,
'events' => array(
'name' => 'login'
)
);
$dataString = json_encode($data);
$post_url = 'https://www.google-analytics.com/mp/collect?api_secret=xxxxxxx&measurement_id=xxxxxxxxx';
$ch = curl_init($post_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
When i run the above its not sending any event to google analytics account. I don't know what is the error and how to find it. Need help on this pls.
I believe the main problem in your example, apart from the typo in the $datastring variable, was that the user id was sent as an int, not as a string. My example here works:
$ip = str_replace('.', '', $_SERVER['REMOTE_ADDR']);
$data = array(
'client_id' => $ip,
'user_id' => '123',
'events' => array(
'name' => 'event_serverside'
)
);
$datastring = json_encode($data);
$post_url = 'https://www.google-analytics.com/mp/collect?api_secret=xxxxxxxxxx&measurement_id=xxxxxxxxx';
$ch = curl_init($post_url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $datastring);
curl_setopt($ch, CURLOPT_HTTP_VERSION,CURL_HTTP_VERSION_1_1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $post_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_POST, TRUE);
$result = curl_exec($ch);

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);

json to php array conversion from REST service

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

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);

Convert POSTMAN Data to array / object to send it to server

I have a postman API. This is the screenshot.
I want to send this data to my url using PHP Curl. I tried everything but it says that merchant_id is missing. Please can anyone guide me how to post these parameters to CURL and how to get appropriate response? Thanks in advance.
UPDATE
This is my PHP Code.
$form_data = json_decode($_POST['form_data']);
$data = array(
'Request' => 'ValidateAddress',
'address' => test_input($form_data->address),
'secondAddress' => test_input($form_data->secondAddress),
'city' => test_input($form_data->city),
'country' => test_input($form_data->country),
'name' => test_input($form_data->name),
'zipCode' => test_input($form_data->zipCode),
'merchant_id' => 'shipm8',
'hash' => '09335f393d4155d9334ed61385712999'
);
$data = json_encode($data);
// $data = '{
// "Request" : "ValidateAddress",
// "address" : "'.test_input($form_data->address).'",
// "secondAddress" : "'.test_input($form_data->secondAddress).'",
// "city" : "'.test_input($form_data->city).'",
// "country" : "'.test_input($form_data->country).'",
// "name" : "'.test_input($form_data->name).'",
// "zipCode" : "'.test_input($form_data->zipCode).'",
// "merchant_id" : "shipm8",
// "hash" : "09335f393d4155d9334ed61385712999"
// }';
$url = 'https://ship2you.com/ship2you/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// if(curl_exec($ch) === false)
// {
// echo 'Curl error: ' . curl_error($ch);
// } else {
$result = curl_exec($ch);
//}
curl_close($ch);
$json_result = json_decode($result, true);
echo '<pre>';print_r($json_result);echo '</pre>';
Try my code .
$form_data = json_decode($_POST['form_data']);
$data = array(
'Request' => 'ValidateAddress',
'address' => test_input($form_data->address),
'secondAddress' => test_input($form_data->secondAddress),
'city' => test_input($form_data->city),
'country' => test_input($form_data->country),
'name' => test_input($form_data->name),
'zipCode' => test_input($form_data->zipCode),
'merchant_id' => 'shipm8',
'hash' => '09335f393d4155d9334ed61385712999'
);
//$data = json_encode($data);
// $data = '{
// "Request" : "ValidateAddress",
// "address" : "'.test_input($form_data->address).'",
// "secondAddress" : "'.test_input($form_data->secondAddress).'",
// "city" : "'.test_input($form_data->city).'",
// "country" : "'.test_input($form_data->country).'",
// "name" : "'.test_input($form_data->name).'",
// "zipCode" : "'.test_input($form_data->zipCode).'",
// "merchant_id" : "shipm8",
// "hash" : "09335f393d4155d9334ed61385712999"
// }';
$url = 'https://ship2you.com/ship2you/';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
//curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
// if(curl_exec($ch) === false)
// {
// echo 'Curl error: ' . curl_error($ch);
// } else {
$result = curl_exec($ch);
//}
curl_close($ch);
$json_result = json_decode($result, true);
echo '<pre>';print_r($json_result);echo '</pre>';

Categories