Convert nested array to json in PHP without additional coding - php

I want to convert my array to a Json String and use it for send message using Firebase Cloud Messaging Server.
My array is :
$data = array(
"to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
"notification" =>
array(
"body" => "sadeq",
"title" => "test notification"
)
);
and when I use json_encode($data) my back String is:
{"to":"cMbucIFcJMA:APA91bH_Wq0sPr.... \n","notification":"Array"}
how can I convert this array to valid Json without have Array in my notification String???
My completely function is:
public function SendFromPost(){
$data = array(
"to" => "cMbucIFcJMA:APA91bH_..... ",
"notification" =>
array(
"body" => "sadeq",
"title" => "test notification"
)
);
$ch = curl_init();
curl_setopt($ch , CURLOPT_URL , "https://fcm.googleapis.com/fcm/send");
curl_setopt($ch , CURLOPT_POST , 1);
curl_setopt($ch , CURLOPT_POSTFIELDS , $data );
curl_setopt($ch , CURLOPT_RETURNTRANSFER , true);
$headers = [
'Content-Type: application/json \n',
'Authorization: key=AIzaS.......'
];
curl_setopt($ch , CURLOPT_HTTPHEADER , $headers);
$server_output = curl_exec($ch);
curl_close($ch);
return var_dump(json_encode($data));
}
My code is correct. but I don't know why my php do like this.

Your code works. You've got an extra ; that isn't valid after your nested array.
<?php
$data = array(
"to" => "cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...",
"notification" =>
array(
"body" => "sadeq",
"title" => "test notification"
)
);
var_dump(json_encode($data));
Yields
string(115) "{"to":"cMbucIFcJMA:APA91bH_Wq0sPrMhTmhJ9gPJX7GUsRo...","notification":{"body":"sadeq","title":"test notification"}}"

Related

Send image as attachment as well as inline using Sendgrid API

I want to send an email with the image as an attachment and also embed it in the body.
<?php
$email = "to#example.com";
$name = "some_name";
$img = file_get_contents('image.jpg');
$body = '<img src = "cid:image">';
$subject = "Test email";
$headers = array(
'Authorization: Bearer API_KEY',
'Content-Type: application/json'
);
$data = array(
"personalizations" => array(
array(
"to" => array(
array(
"email" => $email,
"name" => $name
)
)
)
),
"from" => array(
"email" => "from#example.com"
),
"subject" => $subject,
"content" => array(
array(
"type" => "text/html",
"value" => $body
)
),
"attachments" => array(
array(
"content" => base64_encode($img),
"type" => "image/jpeg",
"filename" => "image",
"disposition" => "inline",
"content_ID" => "image",
//"disposition" => "attachment"
)
)
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.sendgrid.com/v3/mail/send");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($ch);
curl_close($ch);
echo $response;?>
The problem is that it is either going as inline content or an attachment but not both. I don't know how to solve this.
I tried adding two separate attachments blocks for inline and attachment, but it's always considering the second block.
Nothing seems to work.
Twilio SendGrid developer evangelist here.
You don't want to set two of the same keys in an array (as you are doing for disposition) or set two attachments blocks. Instead, you should add two items to the attachments block, like this:
"attachments" => array(
array(
"content" => base64_encode($img),
"type" => "image/jpeg",
"filename" => "image-inline",
"disposition" => "inline",
"content_ID" => "image-inline",
),
array(
"content" => base64_encode($img),
"type" => "image/jpeg",
"filename" => "image-attachment",
"disposition" => "attachment",
"content_ID" => "image-attachment",
),
)
Notice I also provided different filenames and content IDs for the inline and attached files.

Requesting Api Call using cURL

Someone could help me ? I'm trying to do a request by the code bellow, but anything happen, any message appears. I believe my code it's right:
public function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
));
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => array('Content-type: application/json') ,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options );
$result = curl_exec($ch); // Getting jSON result string
print_r($result);
}
Find link with instructions of the site:
you will reiceive this:
[
{
"Code": 114,
"Message": "The provided MerchantId is not in correct format"
}
]
with this code:
function subscribe(){
$json_url = 'https://apisandbox.cieloecommerce.cielo.com.br/1/sales/';
$json_string = json_encode(
array(
"MerchantOrderId"=>"2014113245231706",
"Customer" => array(
"Name" => "Comprador rec programada"
),
"Payment" => array(
"Type" => "CreditCard",
"Amount" => 1500,
"Installments" => 1,
"SoftDescriptor" => "Assinatura Fraldas"
)
)
);
$headers = array(
'Content-Type: application/json',
'MerchantId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'MerchantKey: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx',
'RequestId: xxxxxxxx-xxxxx-xxxxx-xxxxx-xxxxxxxxxxxx'
);
$ch = curl_init($json_url);
$options = array(
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => $headers,
CURLOPT_POSTFIELDS => $json_string
);
curl_setopt_array( $ch, $options ); $result = curl_exec($ch);
print_r($result);
}
subscribe()
It would be interesting what HTTP status code you get:
print_r(curl_getinfo($ch, CURLINFO_HTTP_CODE));

I need a code to get emails of certain companies using freebase API in php

All i know is company name and its country. Can anyone provide a sample php code. On Running this code I get an error property not found, "organisation email contact".
<?php
$service_url = 'https://www.googleapis.com/freebase/v1/search';
$params = array(
'query' => 'Emirates',
'key' => "My-Key",
'filter' => '(all type:/business/business_operation)',
"output" => '(/organization/email_contact )',
// "result" => array(
// "/organization/organization/email" => [],
// "name" => "Freebase Staff",
// "id" => "/business/business_operation"
// )
);
$url = $service_url . '?' . http_build_query($params);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$response = json_decode(curl_exec($ch), true);
curl_close($ch);
print "<pre>";print_r($response);print "</pre>";
?>
Try changing the output field parameter value:
"output" => '(/organization/email_contact )' to "output" =>
'(all/organization/email_contact)'

how to send the JSON also from the PHP API

I'm sending a text push from the php API code successfully, but I wonder how to send the JSON also from the PHP API
My problem is that when I send JSON from the PHP API code it received like like a "message" type.
When i send the same JSON code from the parse control panel it works fine
I so some hint to send "uri" key in the data, but it didn't help.
What am I missing?
Thanks.
this is the PHP code that i'm using
<?php
$APPLICATION_ID = "gggggggggggggggg";
$REST_API_KEY = "xxxxxxxxxxxxxxxxxxx";
//$MESSAGE = "your-alert-message";
if (!empty($_POST)) {
$errors = array();
foreach (array('app' => 'APPLICATION_ID', 'api' => 'REST_API_KEY', 'body' => 'MESSAGE') as $key => $var) {
if (empty($_POST[$key])) {
$errors[$var] = true;
} else {
$$var = $_POST[$key];
}
}
if (!$errors) {
$url = 'https://api.parse.com/1/push';
if(strstr($MESSAGE,"{")){ //json
$data['data_type']='json';
//$MESSAGE = json_decode($MESSAGE);
}
//, 'uri' => $MESSAGE
$data = array(
'channel' => 'test1',
'type' => 'android',
'expiry' => 1451606400,
'data_type' => 'json',
'data' =>array(
'alert'=> "the link2",
'uri' => $MESSAGE
),
'uri' => $MESSAGE
);
//var_dump( $data );die;
//if(strstr($MESSAGE,"{")) //json
//$data['data_type']='json';
$_data = json_encode($data);
//var_dump( $_data );die;
$headers = array(
'X-Parse-Application-Id: ' . $APPLICATION_ID,
'X-Parse-REST-API-Key: ' . $REST_API_KEY,
'Content-Type: application/json',
'Content-Length: ' . strlen($_data)
);
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $_data);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
}
}
?>
In the parse.com website there is a tool that you can send PUSH and in this tool you can send push with 2 types: plain text, or JSON.
it's look like that
When I try to send push with this parse.com tool in both types it works fine and I get the push properly
But, when I try to send to push from my PHP API code as a "JSON" I always got it as a "plain text"
What am I'm doing wrong ?
It depends on your JSON structure for example i want to send this:
{
"data": {
"date": "2015-12-09",
"message": "and when you open this we will show you a message.",
"title": "6 Notice Click On It :)))",
"url": ""
},
"is_background": false
}
and in your php you should send like this:
$data = array(
'where' => '{}', // send to all users
// 'channels' => '{my_channel_name}',
'data' => array(
'is_background'=>false,
'data'=>array(
'date'=>'2015-12-09',
'message'=>'and when you open this we will show you a message',
'title'=>' Notice Click On It',
'url'=>''
),
),
);

Use collapse key for 2 type ofmessages gcm

In my gcm android app I am sending 2 types of messages from application server.I got the idea about what is collapse key, but Idont know how to use.These are the two types of messages.
1.
$message = array(
"price" => "signal",
"type" => $user_type,
"date" => $date1,
"name" => $signal_name,
"buy" => $price,
"stop" => $stop,
"tv" => $trig_value,
"tp" => $profit,
"res" => $result,
);
second one
$message = array(
"price" => "instru",
"price1" => $trade1,
"price2" => "$trade2",
"price3" => "$trade3",
"price4" => "$trade4",
"price5" => "$date"
);
What I need is the last messages send for both of the message types persist in gcm server.How can I do that.I am giving the gcm class also .Please help.
GCM.php
<?php
class GCM {
//put your code here
// constructor
function __construct() {
}
/**
* Sending Push Notification
*/
public function send_notification($registatoin_ids, $message) {
// include config
include_once './config.php';
// Set POST variables
$url = 'https://android.googleapis.com/gcm/send';
$fields = array(
'registration_ids' => $registatoin_ids,
'data' => $message,
);
$headers = array(
'Authorization: key='.GOOGLE_API_KEY,
'Content-Type: application/json'
);
// 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, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// Disabling SSL Certificate support temporarly
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
// Execute post
$result = curl_exec($ch);
if ($result === FALSE) {
die('Curl failed: ' . curl_error($ch));
}
// Close connection
curl_close($ch);
echo $result;
}
}
?>
You should add the collapse_key parameter to your JSON.
The JSON should look like this :
For example, for the first type :
{
"registration_ids":["...", "..."],
"collapse_key": "type1",
"data": {
"price" => "...",
"type" => "...",
...
},
}
For the second type, give a different value to collapse_key.
Based on your code and my limited knowledge of PHP, you need something like this :
$fields = array(
'collapse_key' => $collapse_key,
'registration_ids' => $registatoin_ids,
'data' => $message,
);
And the $collapse_key should be initialized based on the type of data you have in $message.

Categories