I'm working with API of a delivery service. They provide an opportunity to test the API on their website, where the following code works perfectly:
{
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
But when I try to convert it to PHP format, I don't know what to do with the arrays of 'methodProperties' in PHP syntax.
$data = array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => ???
);
Can you please help me to convert the code to PHP correctly?
You need to understand how json_encode and json_decode functions work:
This as JSON string:
{
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
is equivalent to this in PHP:
array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array(
'Documents' => array(
"20450000773554",
"20450000773555"
)
)
);
Try that
<?php
$data = array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array('Documents' => array('20450000773554', '20450000773554'))
);
echo json_encode($data);
?>
JSON :
$json = {
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
the data of this format is known as JSON(Javascript object notation),So,If you want to access it by using PHP you have to decode it using json_decode predefined function in PHP.
PHP:
$decoded_string = json_decode($json);
now use,
echo "<pre>";
print_r($decoded_string);
you get the following data in the form of array and you can easily parse this data in your application.
array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array(
'Documents' => array(
"20450000773554",
"20450000773555"
)
)
);
Related
Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values
I recently tried to use ES. So I set it up in a cloud 9 environnement. I inserted data using a curl request file and I can see them with
http://mydomain/ingredients/aliments/_search?size=350&pretty=true
I then tried to set up elastic SDK (v.2.0) with Silex but I can't get the same output...
Here is my code :
$client = $app['elasticsearch'];
$params = array(
'size' => 350,
'index' => 'ingredients',
'type'=>'aliment',
'body' => array(
'query'=>array(
'match_all' => new \stdClass()
)
)
);
$ingredients = $client->search($params);
The output is NULL but when I do the following :
$params = array(
'index' => 'ingredients',
'type' => 'aliment'
);
$count = $client->count($params);
The output is as expected : {"count":240,"_shards":{"total":5,"successful":5,"failed":0}}
I've already spent a few hours trying to figure what's going on, I tried to replace the 'query' args with a json string, I tried empty array instead of the new stdClass but nothing seems to work.
Edit : I read the documentation again and tried the official example :
$client = $app['elasticsearch'];
$params = [
"search_type" => "scan", // use search_type=scan
"scroll" => "30s", // how long between scroll requests. should be small!
"size" => 50, // how many results *per shard* you want back
"index" => "ingredients",
"body" => [
"query" => [
"match_all" => []
]
]
];
$output = $client->search($params);
$scroll_id = $output['_scroll_id']; /*<<<This works****/
while (\true) {
// Execute a Scroll request
$response = $client->scroll([
"scroll_id" => $scroll_id, //...using our previously obtained _scroll_id
"scroll" => "30s" // and the same timeout window
]
);
var_dump($response); /*<<<THIS IS NULL****/
...
}
And unfortunately got same null result...
What am I doing wrong ?
Thanks for reading.
In my case it works this way:
$json = '{
"query": {
"match_all": {}
}
}';
$params = [
'type' => 'my_type',
'body'=> $json
];
I found out that the inserted data was malformed.
Accessing some malformed data via browser URL seems to be OK but not with a curl command line or the SDK.
Instead of {name:"Yaourt",type:"",description:""} , I wrote {"name":"Yaourt","description":""} in my requests file and now everything work as expected !
#ivanesi 's answer works. You may also try this one:
$params["index"] = $indexName;
$params["body"]["query"]["match_all"] = new \stdClass();
I was not able to find a working example on how to query Elasticsearch using the completion suggester in PHP (elasticsearch-php).
Querying via CURL, e.g.
curl -X POST 'localhost:9200/tstidx/_suggest?pretty' -d '{
"try" : {
"text" : "a",
"completion" : {
"field" : "suggest"
}
}
}'
works, so the only problem is the query part in PHP.
How do I use the API to query Elasticsearch using the completion suggester?
The PHP ES client has a method called suggest that you can use for that purpose:
$params = [
'index' => 'tstidx',
'body' => [
'try' => [
'text' => 'a',
'completion' => [ 'field' => 'suggest' ]
]
]
];
$client = ClientBuilder::create()->build();
$response = $client->suggest($params);
Using the PHP elasticsearch API
<?Php
include 'autoload.php';
$elastic_search = new ElasticApiService();
$search_params = array(
'index' => 'my_index',
'search_type' => 'match',
'search_key' => 'citynamefield',
'search_value' => 'orlando'
);
$search_results = $elastic_search->searchElastic($search_params);
echo '<pre>';
print_r($search_results);
I have integrated the Wepay payment gateway. But I have facing a problem to pass json object to wepay. It always shows a incorrect json format. Please look at the below code.
$forca_a = array(
'debit_opt_in'=>true
);
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>xxxxx)
)
)
);
If I won't pass the country_options, its seems to working but If I pass this parameter, it always give me an error says "Incorrect JSON format".
I sent an email to wepay help center. They told me that, you are passing the string "country_options":"{"debit_opt_in":true}" <--- this is a string Instead of "country_options":{"debit_opt_in":true} <--- this is a JSON object. So I'm confused. I have no idea how do I pass the JSON object. There is only way and is json_encode($object).
hey use below code to get proper json
<?php
$forca_a = array(
'debit_opt_in'=>true
);
// $forca = json_encode($forca_a);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca_a,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>'xxxxx')
)
)
);
print_r(json_encode($wepay_create_array));
?>
this code will give following json output
{
"name": "xxxx",
"description": "xxxxxxxxx xxxx",
"callback_uri": "xxxxxxx",
"country": "CA",
"currencies": ["CAD"],
"country_options": {
"debit_opt_in": true
},
"rbits": [{
"receive_time": 1461561030,
"type": "website_uri",
"source": "partner_database",
"properties": {
"uri": "xxxxx"
}
}]
}
You have no need to make:
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
before you put it to $wepay_create_array.
Before sending request, i think, you make json_encode($wepay_create_array), and yes, after that you will have 'string' for country_options key.
I need to write a new geoJSON feature to a data.json file using php. Right now I'm writing my data to the file like so:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata []= array(
'measure_location'=> $_POST["measure_location"],
'measure_type'=> $_POST["measure_type"],
'measurement'=> $_POST["measurement"],
'note_text'=> $_POST["note_text"]
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
And this is what the data then looks like in data.json:
{
"measure_location": "52.370611247493486, 4.91587221622467",
"measure_type": "negative",
"measurement": "violence",
"note_text": ""
}
Could I adjust my PHP code to make the data look like so:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"4.91587221622467",
"52.370611247493486"
]
},
"properties": {
"type": "negative",
"input": "violence",
"note": ""
}
}
Got the answer thanks to charlietfl. Changed the php code to:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
I cannot the code that works for you. I have tried many times. It produced a wrong format JSON. The correct code should be,
$jsondata -> features [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);