I want to send request via post method with API, and when sending values, sometimes I need to send two values instead of one, and for this I need to loop it. The solution to this is, before sending the request, I save it to the array in the loop and try to complete the process by making json_encode.
My explanation may not be fully explanatory, so I will explain through the codes.
The request I want to throw is normally like this:
CURLOPT_POSTFIELDS =>'
[
{
"items":
[
{
"name":"string",
"sku":"string",
}
],
}
]'
But some times the items value needs to have two instead of one. For example:
CURLOPT_POSTFIELDS =>'
[
{
"items":
[
{
"name":"string",
"sku":"string",
},
{
"name":"string",
"sku":"string",
}
],
}
]'
So before i make this request i am saving these values to array in a foreach loop.
$data =array();
foreach ($request->orderItems as $orderItemId) {
$order_item = OrderItem::where('orderItemId',$orderItemId)->first();
$data[] = array(
"sku"=> $order_item->sku,
"name"=> $order_item->name,
)
}
And if I'm going to send more than one value, my final code looks like this.
CURLOPT_POSTFIELDS =>'
[
{
"items": '.json_encode($data).',
}
]'
Here is where the problem starts and when i try to send this request i get this error:
Array to string conversion
What should I do exactly? Where am I missing?
You might be missing the Content-Type header for your cURL call.
CURLOPT_HTTPHEADER => [
'Content-Type' => 'application/json',
],
Try to encode all the content in CURLOPT_POSTFIELDS like this way
$array = [
array(
"name" => "string",
"sku" => "string",
),
array(
"name" => "string",
"sku" => "string",
)
];
$final = json_encode([["items" => $array]]);
//now use this variable directly in CURLOPT_POSTFIELDS
CURLOPT_POSTFIELDS => $final
may it helps ....
Related
I'm building and API feed using Element API plugin from Craft, and I'd like the data output to be serialized as a hash, but currently it's returning an array, as example bellow:
<?php
namespace Craft;
return [
'endpoints' => [
'event-name/feed.json' => [
'elementType' => ElementType::Entry,
'criteria' => ['section' => 'event1'],
'transformer' => function(EntryModel $entry) {
$speakersList = [];
foreach ($entry->speakersList as $speaker) {
$speakersList[] = [
'name' => $speaker->speakerFullName,
'jobTitle' => $speaker->speakerJobTitle,
'company' => $speaker->speakerCompany,
];
}
return [
'speakers' => $speakersList,
];
},
],
];
And the output:
{
"data": [
{
"speakers": [
{
"name": "John Doe",
"jobTitle": "Marketing",
"company": "Company 1",
},
...
I've tried the serialize options in the documentation, but none seemed to solve the issue.
Currently if I'd like to access the speakers within data I'd have to first access index[0] to be able to get to the speakers key.
Is there a way to get rid of this array level?
When you receive a request, your fulfillment must return a response
I have a HTTPS endpoint which receives commands sent thru the google assistant(My Fulfilment URL). But i want to return a text to the user for every request made
Eg:
USER REQUEST : "Tell, 'app name' to do blah blah"
ASSISTANT RESPONSE : "Okay, sure"
As documented in this article --> https://developers.google.com/actions/components/fulfillment (RESPONSE FORMAT) , I have coded the json file according to the format said in the above link
But it says your fulfillment must return a response
RESPONSE.JSON
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
"textToSpeech": "sure thing",
"displayText": "Sure, thing!"
}
]
}
}
In my Fulfilment end point i did the above.
fulfilment.php
$file = [
"expectUserResponse" => false,
"finalResponse" => [
"richResponse" => [
"items" => [
[
"simpleResponse" => [
"textToSpeech" => "Sure thing!",
"displayText" => "Sure, thing?"
]
]
]
]
]
];
echo json_encode($file);
header('Content-Type: application/json');
How do i return this file in php back to google assistant?
I am using PHP :)
For starters - that isn't valid JSON. Valid JSON would look something like this:
{
"finalResponse": {
"richResponse": {
"items": [{
"simpleResponse": {
"textToSpeech": "sure thing",
"displayText": "Sure, thing!"
}
}]
}
}
}
Notice the opening and closing brackets to designate that this is a JSON object. What you're sending is a string that has been encoded as a JSON string. Using PHP, the easiest way to create valid JSON is to use json_encode and pass it a nested associative array. So something like this would generate it.
<?php
header('Content-Type: application/json');
$a = [
"finalResponse" => [
"richResponse" => [
"items" => [
[
"simpleResponse" => [
"textToSpeech" => "Sure thing!",
"displayText" => "Sure, thing?"
]
]
]
]
]
];
echo json_encode($a);
Note that the header() must come before anything, even a blank line, has been sent.
However... that might not be your only problem.
This doesn't look like it has all the fields that you should reply. If you're only sending a finalResponse, then you probably also need to set expectUserResponse to false.
(And are you sure that you want to end the conversation every time?)
I'm not sure if anything has changed, but I'm sure, it was possible to pass an array like this:
This request would end up in array (php):
[
'title' => 'Article',
'author' => [
'first_name' => 'John',
'last_name' => 'Doe'
]
]
But if I try send this request now, it is no more possible and sends request like this:
[
'title' => 'Article',
'author[first_name]' => 'John',
'author[last_name]' => 'Doe'
]
What am I doing wrong? How can I achieve sending nested array?
Thanks.
If you pass things like that it will end up as strings on your server. If you are actually trying to pass nested/associative data you can change your body to raw and select JSON as the content-type.
{
"title" : "Article",
"author": {
"first_name": "John",
"last_name" : "Doe"
}
}
I am building a Facebook bot using api.ai and I have gotten to a point where I need to send responses using Facebook generic template. I fetch the list of items to listed from the database and put them in an array and assign to a variable. My problem is that the data is actually returned as shown by Ngrok but it not shown on Facebook as a generic template. Nothing shows. Here is my code.
while($result = mysqli_fetch_assoc($res)){
$array[] = array(
"title"=> $result['title'],
"image_url"=> $result['img_url'],
"subtitle"=> "See all our colors",
"buttons"=>[
[
"type"=>"postback",
"title"=>$result['title'],
"payload"=>$result['payload_id']
]
]
);
}
if ($intentName == "sex"){
$data =json_encode([
'speech' => "Hi ".$firstname,
'displayText' => "test",
'source' => "source",
'data' => ["facebook" => [
"attachment"=>[
"type"=>"template",
"payload"=>[
"template_type"=>"generic",
"elements"=>[
//One attachment
$array
//First attachment ends
]
]
] ]
]
]);
echo $data;
}
I solved it. It should have been:
"elements"=> $array
I using Phalcon PHP as PHP MVC Framework with MongoDB.
I can find object according with some criteria:
$user = User::findFirst(array(array('username' => $login, 'email'=> $login)));
As you can note, this request will return me the record according logical AND operator between conditions. I need to form request that will return result according with OR operator between conditions.
The problem also is that I'm using MongoDB, so, as I can suppose, I can't write PHQL request manually.
Just a matter of mangling PHP arrays
$user = User::findFirst( array(
'$or' => array(
array( 'username' => $login),
array( 'email' => $login)
)
));
So not only do I show the answer but also how my totals non PHP mind solves this problem:
$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
echo var_dump( json_decode( $result ) );
$test = array(
'$or' => array(
array( 'username' => 'login'), array( 'email' => 'login')
)
);
echo json_encode( $test ) ."\n"
So in just a few lines we converted and proved. So since you knew the JSON from either the manual page or reading another question on SO, just convert it. And it's one of the reasons I submit the valid JSON in responses here, is so that the logic can be translated into just about any language implementation.
You can pass column names as string in first param:
$user = User::findFirst('username = "'.$login.'" OR email = "'.$login.'"');
$result = '{ "$or": [ { "username": "login" }, { "email": "login" } ] }';
User::findFirst(array(json_decode($query,true)));
$result is the exact json which can be used to trigger queries in mongodb command line
json_decode with 2nd parameter true will output the array style format of JSON