I have a problem need to join or merge two or more json file..
so far here's my code:
//first
$url1="https://www.zopim.com/api/v2/chats";
$ch1 = curl_init();
curl_setopt($ch1, CURLOPT_URL, $url1);
curl_setopt($ch1, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch1, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch1, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch1, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
$output1 = curl_exec($ch1);
$info1 = curl_getinfo($ch1);
curl_close($ch1);
$chats1 = json_decode($output1,true);
//second
$url2="https://www.zopim.com/api/v2/chats?page=2";
$ch2 = curl_init();
curl_setopt($ch2, CURLOPT_URL, $url2);
curl_setopt($ch2, CURLOPT_USERPWD, "$username:$password");
curl_setopt($ch2, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch2, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch2, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
$output2 = curl_exec($ch2);
$info2 = curl_getinfo($ch2);
curl_close($ch2);
$chats2 = json_decode($output2,true);
$r = [];
if(is_array($chats1) && is_array($chats2))
{
foreach($chats1 as $key => $array)
{
$r[$key] = array_merge($chats2[$key], $array);
}
}
else
{
echo 'problem with json';
}
echo json_encode($r, JSON_UNESCAPED_SLASHES);
but i encounter an error:
here's number 44 error line:
hopefully you can help me or do you have a much better code or login for this one.. like using foreach...
I also want to make the link auto generated by number like ?page=1, ?page=2 and so on...
Here's my json:
json1
and json2:
$finalArray = [];
$finalArray[] = json_decode($json1,true);
$finalArray[] = json_decode($json2,true);
$mergedJSON = json_encode($finalArray);
For same array structure you can use
array_merge($array1, $array2)
method & then use
json_encode().
Example:
$mergedArray = array_merge($array1, $array2);
$mergedJSON = json_encode($mergedArray);
I have create two small json for join it ! Check below,
Json - 1
{
"chats": [
{
"comment": null,
"triggered_response": true,
"visitor": {
"phone": ""
},
"session": {
"city": "Moncton",
"end_date": "2017-07-03",
"ip": "99.240.22.84"
},
"duration": "32",
"agent_names": {
"name": "test"
}
}
]
}
Json - 2
{
"chats": [
{
"comment": null,
"triggered_response": true,
"visitor": {
"phone": ""
},
"session": {
"city": "Moncton1",
"end_date": "2017-08-03",
"ip": "99.240.22.85"
},
"duration": "321",
"agent_names": {
"name": "test1"
}
}
]
}
Now i join that using array_merge_recursive.
PHP
// $json is first json encoded string same as $json1 is second encoded string.
$merge_array = array_merge_recursive(json_decode($json,true),json_decode($json1,true));
Json encoded Output
{
"chats": [
{
"comment": null,
"triggered_response": true,
"visitor": {
"phone": ""
},
"session": {
"city": "Moncton",
"end_date": "2017-07-03",
"ip": "99.240.22.84"
},
"duration": "32",
"agent_names": {
"name": "test"
}
},
{
"comment": null,
"triggered_response": true,
"visitor": {
"phone": ""
},
"session": {
"city": "Moncton1",
"end_date": "2017-08-03",
"ip": "99.240.22.85"
},
"duration": "321",
"agent_names": {
"name": "test1"
}
}
]
}
If your both array structure same Here you pass $chats2[$key] as string on array_merge(); so error occurred
$res_arr = array_merge($chats2,$chats1);
array_values($res_arr);
$r = [];
if(!empty($res_arr))
{
foreach($res_arr as $key => $array)
{
$r[$key] = $array;
}
}
else
{
echo 'problem with json';
}
echo json_encode($r);
You can do this:
$user = array();
$user[] = json_decode($json1,true);
$user[] = json_decode($json2,true);
$json_merge = json_encode($user);
Related
I run curl_multi_getcontent function to send all api request at once. As a return I get one big array.
Inside this array each url content is being save as string. Can someone please tell me how to change my code so the url content would return as array.
function multiRequest($data, $options = array()) {
$curly = array();
$result = array();
$mh = curl_multi_init();
$headers = array(
"api host",
"api key"
);
foreach ($data as $id => $d) {
$curly[$id] = curl_init();
$url = (is_array($d) && !empty($d['url'])) ? $d['url'] : $d;
curl_setopt($curly[$id], CURLOPT_URL, $url);
curl_setopt($curly[$id], CURLOPT_HTTPHEADER,$headers);
curl_setopt($curly[$id], CURLOPT_RETURNTRANSFER, 1);
if (is_array($d)) {
if (!empty($d['post'])) {
curl_setopt($curly[$id], CURLOPT_POST, 1);
curl_setopt($curly[$id], CURLOPT_POSTFIELDS, $d['post']);
}
}
if (!empty($options)) {
curl_setopt_array($curly[$id], $options);
}
curl_multi_add_handle($mh, $curly[$id]);
}
$running = null;
do {
curl_multi_exec($mh, $running);
} while($running > 0);
foreach($curly as $id => $c) {
$result[$id] = curl_multi_getcontent($c);
curl_multi_remove_handle($mh, $c);
}
curl_multi_close($mh);
}
and below is example of a output which looks like array but is a sting.
Array
(
[0] =>
{
"api": {
"results": 38,
"fixtures": [
{
"fixture_id": 210282,
"league_id": 761,
"league": {
"name": "NB II",
"country": "Hungary",
"logo": null,
},
"event_date": "2019-08-04T17:00:00+00:00",
"event_timestamp": 1564938000,
"firstHalfStart": 1564938000,
"secondHalfStart": 1564941600,
},
{
"fixture_id": 210285,
"league_id": 761,
"league": {
"name": "NB II",
"country": "Hungary",
"logo": null,
},
"event_date": "2019-08-07T15:30:00+00:00",
"event_timestamp": 1565191800,
"firstHalfStart": 1565191800,
}
]
}
}
[1] => and so on
)
I am trying to post this JSON in post with URL
$url = 'https://api.havail.sabre.com/v1.2.0/air/ticket';
$headers2 = array(
'Authorization: bearer '.$access_token,
'protocol: HTTP 1.1 ',
'Accept: */*',
"Content-Type: application/json"
);
$postData ='{
"AirTicketRQ": {
"DesignatePrinter": {
"Profile": {
"Number": 1
}
},
"Itinerary": {
"ID": "VWKJJT"
},
"Ticketing": [{
"FOP_Qualifiers": {
"BSP_Ticketing": {
"MultipleFOP": {
"Fare": {
"Amount": "100.00"
},
"FOP_One": {
"CC_Info": {
"Suppress": true,
"PaymentCard": {
"Code": "VI",
"ExpireDate": "2016-11",
"ExtendedPayment": 12,
"Number": ***********1003
}
}
},
"FOP_Two": {
"Type": "CK"
}
}
}
},
"PricingQualifiers": {
"PriceQuote": [{
"Record": [{
"Number": 1,
"Reissue": true
}]
}]
}
},
{
"FOP_Qualifiers": {
"BSP_Ticketing": {
"MultipleFOP": {
"Fare": {
"Amount": "100.00"
},
"FOP_One": {
"CC_Info": {
"Suppress": true,
"PaymentCard": {
"Code": "VI",
"ExpireDate": "2016-11",
"ExtendedPayment": 12,
"Number": ************1003
}
}
},
"FOP_Two": {
"Type": "CA"
}
}
}
},
"PricingQualifiers": {
"PriceQuote": [{
"Record": [{
"Number": 2,
"Reissue": true
}]
}]
}
}],
"PostProcessing": {
"EndTransaction": {
"Source": {
"ReceivedFrom": "SPTEST"
}
}
}
}
}';
$ch2 = curl_init();
curl_setopt($ch2,CURLOPT_HTTPHEADER,$headers2);
curl_setopt($ch2, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, POST);
curl_setopt($ch2, CURLOPT_POSTFIELDS, $postData);
//curl_setopt($curl_handle, CURLOPT_HTTPGET, TRUE);
//curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
//var_dump( $results = json_decode(curl_exec($ch2)));
$results["get_data"] = json_decode(curl_exec($ch2),true);
I tried to use GET method for some other API and it was working. But for Enhanced Air ticket I am getting wrong data in response.
First Part:
Second Part:
What is the printer error and all. I used some get APIs that worked but why this API showing those problems? What is the actual problem? Is my JSON is correct that I am sending in request?
The problem is on this part of the code:
"DesignatePrinter": {
"Profile": {
"Number": 1
}
},
If this used to work, the you probably done it in a different environment or PCC.
I want to use API of the constant contact and want to insert user Email Ids using PHP script while user register to the website.
I using following code for this.
$data['addresses'][0]['address_type'] = 'BUSINESS';
$data['addresses'][0]['city'] = 'Belleville';
$data['addresses'][0]['country_code'] = 'CA';
$data['addresses'][0]['line1'] = '47 Shawmut Ave.';
$data['addresses'][0]['line2'] = 'Suite 404';
$data['addresses'][0]['postal_code'] = '"K8b 5W6';
$data['addresses'][0]['state_code'] = 'ON';
$data['lists'][0]['id'] = "1554397204";
$data['cell_phone'] = "555-555-5555";
$data['company_name'] = "System Optimzations";
$data['confirmed'] = false;
$data['email_addresses'][0]['email_address'] = "username112#example.com";
$data['fax'] = "555-555-5555";
$data['first_name'] = "Manvendra";
$data['home_phone'] = "555-555-5555";
$data['job_title'] = "Systems Analyst 3";
$data['last_name'] = "Rajpurohit";
$data['prefix_name'] = "Mr.Martone";
$data['work_phone'] = "555-555-5555";
$jsonstring = json_encode($data);
// echo '<pre>'; print_r($data);
$posturl = "https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=*******";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
//curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
// curl_setopt($ch, CURLOPT_USERPWD, $authstr);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonstring);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json",'Authorization: Bearer *****
','Content-Length: ' . strlen($jsonstring)));
curl_setopt($ch, CURLOPT_HEADER, false); // Do not return headers
//curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0); // If you set this to 0, it will take you to a page with the http response
$response = curl_exec($ch);
if (FALSE === $response)
throw new Exception(curl_error($ch), curl_errno($ch));
echo '<pre>'; print_r($response); die;
curl_close($ch);
When I run this script then its showing following error.
[{"error_key":"json.payload.empty","error_message":"JSON payload cannot be empty."}]
Please help me that how can I resolve this error.
The actual problem is validation error,which is:-
[{"error_key":"json.max.length.violation","error_message":"#/prefix_name: Value exceeds maximum length of 4."}]
So what i did is changed:-
$data['prefix_name'] = "Mr.Martone";
To:-
$data['prefix_name'] = "tone"; // length need to be 4 or less only
And used this CURL request and data saved successfully.
<?php
$data['addresses'][0]['address_type'] = 'BUSINESS';
$data['addresses'][0]['city'] = 'Belleville';
$data['addresses'][0]['country_code'] = 'CA';
$data['addresses'][0]['line1'] = '47 Shawmut Ave.';
$data['addresses'][0]['line2'] = 'Suite 404';
$data['addresses'][0]['postal_code'] = '"K8b 5W6';
$data['addresses'][0]['state_code'] = 'ON';
$data['lists'][0]['id'] = "1554397204";
$data['cell_phone'] = "555-555-5555";
$data['company_name'] = "System Optimzations";
$data['confirmed'] = false;
$data['email_addresses'][0]['email_address'] = "username112#example.com";
$data['fax'] = "555-555-5555";
$data['first_name'] = "Manvendra";
$data['home_phone'] = "555-555-5555";
$data['job_title'] = "Systems Analyst 3";
$data['last_name'] = "Rajpurohit";
$data['prefix_name'] = "tone";
$data['work_phone'] = "555-555-5555";
$jsonstring = json_encode($data);
//echo '<pre>'; print_r($data);
$posturl = "https://api.constantcontact.com/v2/contacts?action_by=ACTION_BY_OWNER&api_key=*******";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $posturl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonstring);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/json",'Authorization: Bearer ******')); //check change here
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);// this need to be 1
$response = curl_exec($ch);
if (FALSE === $response)
throw new Exception(curl_error($ch), curl_errno($ch));
echo '<pre>'; print_r($response); die;
curl_close($ch);
Output i got is:-
{
"id": "1519826644",
"status": "ACTIVE",
"fax": "555-555-5555",
"addresses": [{
"id": "9ac8fd40-c2b2-11e7-aa57-d4ae5284344f",
"line1": "47 Shawmut Ave.",
"line2": "Suite 404",
"line3": "",
"city": "Belleville",
"address_type": "BUSINESS",
"state_code": "ON",
"state": "Ontario",
"country_code": "ca",
"postal_code": "\"K8b",
"sub_postal_code": "5W6"
}],
"notes": [],
"confirmed": false,
"lists": [{
"id": "1554397204",
"status": "ACTIVE"
}],
"source": "API",
"email_addresses": [{
"id": "9a914b70-c2b2-11e7-aa57-d4ae5284344f",
"status": "ACTIVE",
"confirm_status": "NO_CONFIRMATION_REQUIRED",
"opt_in_source": "ACTION_BY_OWNER",
"opt_in_date": "2017-11-06T05:23:21.000Z",
"email_address": "username23333#example.com"
}],
"prefix_name": "tone",
"first_name": "Manvendra",
"middle_name": "",
"last_name": "Rajpurohit",
"job_title": "Systems Analyst 3",
"company_name": "System Optimzations",
"home_phone": "555-555-5555",
"work_phone": "555-555-5555",
"cell_phone": "555-555-5555",
"custom_fields": [],
"created_date": "2017-11-06T05:23:20.000Z",
"modified_date": "2017-11-06T05:23:20.000Z",
"source_details": "Web Devloping"
}
I'm trying to implement the Bing Spell Check API v7. This is my current function:
# spell check
function bing_spell_check($q, $lang) {
$param = array();
$param['appName'] = PRO_NAME;
$param['text'] = $q;
$param['setLang'] = $lang;
$url = 'https://api.cognitive.microsoft.com/bing/v7.0/SpellCheck?'.http_build_query($param);
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_TIMEOUT, 10);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_HTTPHEADER,
array(
'Accept: application/ld+json',
'Ocp-Apim-Subscription-Key: '.PRO_BING_KEY_SPELL
)
);
$response = curl_exec($process);
return $response;
}
The problem is that this example:
print_r(bing_spell_check('en', 'whts yur name?'));
Returns:
{
"#context":{
"#vocab":"http:\/\/bingapis.com\/v7\/schemas\/",
"s":"http:\/\/schema.org\/",
"#base":"https:\/\/api.cognitive.microsoft.com\/api\/v7\/"
},
"#type":"SpellCheck",
"flaggedTokens":[
]
}
Which means it has not found any errors. I ran the very same test in Bing's test tool, and I received this structure instead:
{
"_type": "SpellCheck",
"FlaggedTokens": [
{
"Offset": 0,
"Token": "whts",
"Type": "UnknownToken",
"Suggestions": [
{
"suggestion": "what's",
"Score": 0.909352914464075
},
{
"suggestion": "whats",
"Score": 0.810588859407343
},
{
"suggestion": "what is",
"Score": 0.680176771139565
}
]
},
{
"Offset": 5,
"Token": "yur",
"Type": "UnknownToken",
"Suggestions": [
{
"suggestion": "your",
"Score": 0.909352914464075
}
]
}
]
}
Am I missing something. Any ideas? Thanks!
It is quite simple, you just mixed up your function parameters. You have
function bing_spell_check($q, $lang) {}
and
bing_spell_check('en', 'whts yur name?');
That is where the problem starts, $q is now en and $lang is now whts yur name?. Thus when you create your $param array you have the language and the text mixed up (which will cause the Spell Check API to silently fail). You can simply fix this by changing the parameter order:
function bing_spell_check($lang, $q) {}
Now your code
<?php
define(PRO_BING_KEY_SPELL, 'XXX');
define(PRO_NAME, 'XXX');
function bing_spell_check($lang, $q) {
$param = array();
$param['appName'] = PRO_NAME;
$param['text'] = $q;
$param['setLang'] = $lang;
$url = 'https://api.cognitive.microsoft.com/bing/v7.0/spellcheck?'.http_build_query($param);
$process = curl_init();
curl_setopt($process, CURLOPT_URL, $url);
curl_setopt($process, CURLOPT_TIMEOUT, 10);
curl_setopt($process, CURLOPT_RETURNTRANSFER, true);
curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($process, CURLOPT_HTTPHEADER,
array(
'Accept: application/ld+json',
'Ocp-Apim-Subscription-Key: '.PRO_BING_KEY_SPELL
)
);
$response = curl_exec($process);
return $response;
}
print_r(bing_spell_check('en', 'whts yur name?'));
?>
results in
{
"#context": {
"#vocab": "http:\/\/bingapis.com\/v7\/schemas\/",
"s": "http:\/\/schema.org\/",
"#base": "https:\/\/api.cognitive.microsoft.com\/api\/v7\/"
},
"#type": "SpellCheck",
"flaggedTokens": [{
"offset": 0,
"token": "whts",
"type": "UnknownToken",
"suggestions": [{
"suggestion": "what's",
"score": 0.909352914464075
}, {
"suggestion": "whats",
"score": 0.810588859407343
}, {
"suggestion": "what is",
"score": 0.680176771139565
}]
}, {
"offset": 5,
"token": "yur",
"type": "UnknownToken",
"suggestions": [{
"suggestion": "your",
"score": 0.909352914464075
}]
}]
}
I am having problem with Elasticsearch script filter and Curl post URI.
I am passing the values using URL as below
My URL with parameters
$params = rawurlencode('firstName:John');
$url= 'http://localhost:9200/jdbc/_search?q='.$params.'&pretty=true';
My Json code:
$options='{
"query": {
"filtered": {
"filter": {
"script": {
"script": "(min..max).contains(doc.admitted_date.date.year)",
"params": {
"min": 1999,
"max": 2000
}
}
}
}
},
"aggs": {
"citycount": {
"cardinality": {
"field": "cityid",
"precision_threshold": 100
}
}
}
}';
Curl passing:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch,CURLOPT_POSTFIELDS,$options);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$data = ob_get_contents();
ob_end_clean();
When i pass the above query, it show wrong result. because we are passing parameters with URL and JSON in both formats. So one time it will take the parameters from URL only. Is there any way to pass both parameters or is there any other way to pass this? Is there any way to pass Script in URL in Elasticsearch PHP
The correct way of doing this is to pass everything in the query, including the match on the firstName field:
$options='{
"query": {
"filtered": {
"query": {
"query_string": {
"query": "firstName:John"
}
},
"filter": {
"script": {
"script": "(min..max).contains(doc.admitted_date.date.year)",
"params": {
"min": 1999,
"max": 2000
}
}
}
}
},
"aggs": {
"citycount": {
"cardinality": {
"field": "cityid",
"precision_threshold": 100
}
}
}
}';
$url= 'http://localhost:9200/jdbc/_search?pretty=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_POST, 1); <---- also add this
curl_setopt($ch, CURLOPT_POSTFIELDS, $options);
ob_start();
curl_exec ($ch);
curl_close ($ch);
$data = ob_get_contents();
ob_end_clean();