JSON and CURL encoding - php

I have a curl page that output in json format but I can't get json reading from android correctly. I want Json format with just an array only not object and array together. Check the output at the bottom for example. I want to write a php code that encode json that matches below. How would i do that? Thanks.
PHP FILE:
<?php
require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/vendor/mashape/unirest-php/src/Unirest.php';
//$response = Unirest\Request::get("",
// array(
// "host" => "",
// "key" => "
// )
//);
//
//
//echo stripslashes(json_encode($response));
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "json",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_HTTPHEADER, array('Accept: application/json'),
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"host: ",
"KEY: "
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
$json = json_encode($response, JSON_UNESCAPED_SLASHES);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo stripslashes($response);
}
$fp = fopen('results.json', 'w');
fwrite($fp, stripslashes($response));
fclose($fp);
ORIGINAL OUTPUT FROM CURL:
{
"quoteResponse":
{
"result": [{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"quoteSourceName": "Nasdaq Real Time Price",
"exchangeDataDelayedBy": 0,
"regularMarketPrice": 30.69,
"regularMarketTime": 1568404801,
"regularMarketChange": 0.48000145,
"regularMarketVolume": 45547913,
"shortName": "Advanced Micro Devices, Inc.",
"priceHint": 2,
"postMarketChangePercent": 0.0325846,
"postMarketTime": 1568419190,
"postMarketPrice": 30.7,
"postMarketChange": 0.0100002,
"regularMarketChangePercent": 1.5888827,
"regularMarketPreviousClose": 30.21,
"fullExchangeName": "NasdaqGS",
"longName": "Advanced Micro Devices, Inc.",
"market": "us_market",
"pageViews": {
"shortTermTrend": "UP",
"midTermTrend": "UP",
"longTermTrend": "UP"
},
"marketState": "CLOSED",
"exchange": "NMS",
"sourceInterval": 15,
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"gmtOffSetMilliseconds": -14400000,
"esgPopulated": false,
"tradeable": true,
"triggerable": true,
"symbol": "AMD"
}],
"error": null
}
}
THE OUTPUT I WANT IS THIS WITHOUT quoteResponse LIKE ABOVE OUTPUT. CHECK BELOW :
{
"result": [{
"language": "en-US",
"region": "US",
"quoteType": "EQUITY",
"quoteSourceName": "Nasdaq Real Time Price",
"regularMarketPrice": 30.69,
"regularMarketTime": 1568404801,
"regularMarketChange": 0.48000145,
"regularMarketVolume": 45547913,
"sourceInterval": 15,
"exchangeTimezoneName": "America/New_York",
"exchangeTimezoneShortName": "EDT",
"pageViews": {
"shortTermTrend": "UP",
"midTermTrend": "UP",
"longTermTrend": "UP"
},
"gmtOffSetMilliseconds": -14400000,
"market": "us_market",
"postMarketChangePercent": 0.0325846,
"postMarketTime": 1568419190,
"postMarketPrice": 30.7,
"postMarketChange": 0.0100002,
"regularMarketChangePercent": 1.5888827,
"priceHint": 2,
"shortName": "Advanced Micro Devices, Inc.",
"regularMarketPreviousClose": 30.21,
"fullExchangeName": "NasdaqGS",
"longName": "Advanced Micro Devices, Inc.",
"exchange": "NMS",
"exchangeDataDelayedBy": 0,
"esgPopulated": false,
"tradeable": true,
"triggerable": true,
"marketState": "CLOSED",
"symbol": "AMD"
}],
"error": null
}

Decode your JSON, get quoteResponse from it and encode it again.
$json = json_encode(json_decode($json)->quoteResponse);

Related

Getting 401 unauthorzed error while creating order with Shipstation REST API and PHP

I am trying to connect Shipstation with my website using REST API and creating order which can be added to manual store inside Shipstation by default. However, I am getting error 401 unauthorised continuously, even I copied API key and API secret from Shipstation account and passed its base64 form to Authorization header.
Here is my Simple Post Request :
$api_key = 'SS_KEY';
$api_secret = 'SS_SECRET';
$token = base64_encode($api_key.':'.$api_secret);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'https://ssapi.shipstation.com/orders/createorder/',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"orderNumber": "TEST-ORDER-API-DOCS",
"orderStatus": "awaiting_shipment",
"customerUsername": "abc",
"customerEmail": "headhoncho#whitehouse.gov",
"billTo": {
"name": "Inam Ali",
"company": "abc",
"street1": "1",
"street2": null,
"street3": null,
"city": "Pesh",
"state": "KPK",
"postalCode": 25000,
"country": "Pakistan",
"phone": "0315333333",
"residential": true
},
"shipTo": {
"name": "Inam Ali",
"company": "US Govt",
"street1": "1600 Pennsylvania Ave",
"street2": "Oval Office",
"street3": null,
"city": "Washington",
"state": "DC",
"postalCode": "20500",
"country": "US",
"phone": "555-555-5555",
"residential": true
},
"items": [
{
"lineItemKey": "vd08-MSLbtx",
"name": "Test item #1",
"imageUrl": null,
"quantity": 2,
"unitPrice": 99.99,
"taxAmount": 2.5,
}
],
"amountPaid": 218.73,
"taxAmount": 5,
"tagIds": [
53974
]
}',
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'host: ssapi.shipstation.com',
'Authorization: Basic '.$token
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;

Random Characters PHP Decode Nested JSON

Really struggling with this one. I have connected to the API fine and can get the raw JSON Data.
But when I am trying to decode it I just get a load of random characters.
The JSON path should be response->data->fieldData->Case_ID
There are other fields there also but I have hidden them to make it easier to read.
This is my JSON
{
"response": {
"dataInfo": {
"database": "MicroLog",
"layout": "External_API_Cases",
"table": "Cases",
"totalRecordCount": 143691,
"foundCount": 23,
"returnedCount": 2
},
"data": [
{
"fieldData": {
"Case_ID": 139220,
},
"portalData": {},
"recordId": "139261",
"modId": "138"
},
{
"fieldData": {
"Case_ID": 143421,
},
"portalData": {},
"recordId": "143462",
"modId": "25"
}
]
},
"messages": [
{
"code": "0",
"message": "OK"
}
]
}
The code I have been using.
<?php
include('login.php');
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => 'URL_HERE',
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => '',
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 0,
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => 'POST',
CURLOPT_POSTFIELDS =>'{
"query": [
{
"Closed": "1",
"Closed_TimeStamp": "06/24/2021"
}
],
"limit": 2
}',
CURLOPT_HTTPHEADER => array(
'Authorization: Bearer '.$token.'',
'Content-Type: application/json'
),
));
$response = curl_exec($curl);
curl_close($curl);
$decode = json_decode($response,true);
foreach ($decode['response']['data'] as $dec) {
foreach ($dec['fieldData'] as $cd) {
echo $cd['Case_ID'];
}
echo "<br/>";
}
?>
This is what it returns
188B7162M111662J>41ISS1AM1200000000000J5D
118A7162I11162J�62ISS1AM120000000000J5D

Retrieving data poin from API response

I cobbled together some PHP code that allows me get business data from Yelp API v.3
$postData = "grant_type=client_credentials&".
"client_id=MyClientIDl94gqHAg&".
"client_secret=SomEcoDehIW09e6BGuBi4NlJ43HnnHl4S7W5eoXUkB";
// GET TOKEN
$curl = curl_init();
//set the url
curl_setopt($curl,CURLOPT_URL, "https://api.yelp.com/oauth2/token");
//tell curl we are doing a post
curl_setopt($curl,CURLOPT_POST, TRUE);
//set post fields
curl_setopt($curl,CURLOPT_POSTFIELDS, $postData);
//tell curl we want the returned data
curl_setopt($curl,CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($curl);
if($result){
$data = json_decode($result);
}
// GET RESTAURANT INFO
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.yelp.com/v3/businesses/north-india-restaurant-san-francisco",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
"authorization: Bearer ".$data->access_token
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
//close connection
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
The output looks like this:
{"id": "north-india-restaurant-san-francisco", "name": "North India Restaurant", "image_url": "https://s3-media2.fl.yelpcdn.com/bphoto/fIgAIMHGfWRF3I0JmagQ7A/o.jpg", "is_claimed": true, "is_closed": false, "url": "https://www.yelp.com/biz/north-india-restaurant-san-francisco?adjust_creative=qG_bVdazAjjAO1l94gqHAg&utm_campaign=yelp_api_v3&utm_medium=api_v3_business_lookup&utm_source=qG_bVdazAjjAO1l94gqHAg", "phone": "+14153481234", "display_phone": "(415) 348-1234", "review_count": 857, "categories": [{"alias": "indpak", "title": "Indian"}], "rating": 4.0, "location": {"address1": "123 Second St", "address2": "", "address3": "", "city": "San Francisco", "zip_code": "94105", "country": "US", "state": "CA", "display_address": ["123 Second St", "San Francisco, CA 94105"], "cross_streets": ""}, "coordinates": {"latitude": 37.787789124691, "longitude": -122.399305736113}, "photos": ["https://s3-media1.fl.yelpcdn.com/bphoto/howYvOKNPXU9A5KUahEXLA/o.jpg", "https://s3-media2.fl.yelpcdn.com/bphoto/I-CX8nioj3_ybAAYmhZcYg/o.jpg", "https://s3-media3.fl.yelpcdn.com/bphoto/uaSNfzJUiFDzMeSCwTcs-A/o.jpg"], "price": "$$", "hours": [{"open": [{"is_overnight": false, "start": "1000", "end": "2300", "day": 0}, {"is_overnight": false, "start": "1000", "end": "2300", "day": 1}, {"is_overnight": false, "start": "1000", "end": "2300", "day": 2}, {"is_overnight": false, "start": "1000", "end": "2300", "day": 3}, {"is_overnight": false, "start": "1000", "end": "0000", "day": 4}, {"is_overnight": false, "start": "1000", "end": "0000", "day": 5}, {"is_overnight": false, "start": "1000", "end": "2300", "day": 6}], "hours_type": "REGULAR", "is_open_now": true}], "transactions": ["delivery", "pickup"]}
How do I retrieve opening hour on Friday, for example? The day are 0 - 6, Monday - Sunday.
You parse the json data and iterate over the entries:
function getOpeningHoursForDay($data,$day){
$open_hours = $data['hours'][0]['open'];
$n = count($open_hours);
for($i=0;$i<$n;$i++){
if($open_hours[$i]['day']==$day) // check if day matches
return $open_hours[$i];
}
return null; // no matching day found, return null
}
function formatOpeningHour($hour){
return substr($hour,0,2).':'.substr($hour,2); // convert 2300 to 23:00
}
$data = json_decode($response,true);
$friday_hours = getOpeningHoursForDay($data,4);
if(isset($friday_hours)){
echo 'opened ' . formatOpeningHour($friday_hours['start']) . ' - ' .formatOpeningHour($friday_hours['end']);
}else{
echo 'closed';
}

How to format json response from Twitter API to pass in Watson Personality Insight

I wanted to use Personality Insight Service of Watson to analyze the tweets of user. I am using PHP to code. Here is the block of code I am using to get the tweets from Twitter API and input them in PI service of watson.
//Watson PI Parameters
$pi_url = 'https://gateway.watsonplatform.net/personality-
insights/api/v3/profile?version=2016-10-20';
$pi_username = 'XXXX';
$pi_password = 'YYYY';
// auth parameters
$api_key = urlencode('API KEY'); // Consumer Key
$api_secret = urlencode('API Secret'); // Consumer Secret
$auth_url = 'https://api.twitter.com/oauth2/token';
// Twitter Data Parameters
$data_username = 'Screen Name'; // username
$data_count = 10; // number of tweets
$data_url = 'https://api.twitter.com/1.1/statuses/user_timeline.json?
tweet_mode=extended';
// get api access token
$api_credentials = base64_encode($api_key.':'.$api_secret);
$auth_headers = 'Authorization: Basic '.$api_credentials."\r\n".
'Content-Type: application/x-www-form-urlencoded;charset=UTF-
8'."\r\n";
$auth_context = stream_context_create(
array(
'http' => array(
'header' => $auth_headers,
'method' => 'POST',
'content'=> http_build_query(array('grant_type' =>
'client_credentials', )),
)
)
);
$auth_response = json_decode(file_get_contents($auth_url, 0,
$auth_context), true);
$auth_token = $auth_response['access_token'];
// get tweets
$data_context = stream_context_create( array( 'http' => array( 'header' =>
'Authorization: Bearer '.$auth_token."\r\n", ) ) );
$data = file_get_contents($data_url.'&count='.$data_count.
'&screen_name='.urlencode($data_username), 0, $data_context);
print_r($data);
// Pass $data as input to PI
$ch = curl_init();
// Sets the URL cURL will open
curl_setopt($ch, CURLOPT_URL, $pi_url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
)
);
// Here's the HTTP auth
curl_setopt($ch, CURLOPT_USERPWD, $pi_username." : ".$pi_password);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_CAINFO, getcwd() . "\CertificateLocation");
// Makes curl_exec() return server response
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
// And here's the result JSON
$response = curl_exec($ch);
print curl_error($ch);
curl_close($ch);
print_r($response);
I am receiving {
"code": 400,
"sub_code": "S00005",
"error": "Invalid JSON input at line 4, column 28"
} error though.
Can someone please help on how should I pre- format my twitter response so PI can identify it as Json input and analyze it.
EDIT:
Adding the twitter result as answer, as it is too long for comment. Here is the result I am getting with Amazon twitter handle ( tried this just for test)
[{
"created_at": "Thu Apr 20 14:49:27 +0000 2017",
"id": 855070913997492225,
"id_str": "855070913997492225",
"full_text": "#realivanspeaks Aww! We love our customers like Buddy loves a his sugar. \ud83d\ude0d \ud83c\udf6c",
"truncated": false,
"display_text_range": [
16,
76
],
"entities": {
"hashtags": [
],
"symbols": [
],
"user_mentions": [
{
"screen_name": "realivanspeaks",
"name": "Ivan Speaks",
"id": 2484007045,
"id_str": "2484007045",
"indices": [
0,
15
]
}
],
"urls": [
]
},
"source": "\u003ca href=\"https:\/\/www.sprinklr.com\" rel=\"nofollow\"\u003eSprinklr\u003c\/a\u003e",
"in_reply_to_status_id": 855068504642514944,
"in_reply_to_status_id_str": "855068504642514944",
"in_reply_to_user_id": 2484007045,
"in_reply_to_user_id_str": "2484007045",
"in_reply_to_screen_name": "realivanspeaks",
"user": {
"id": 20793816,
"id_str": "20793816",
"name": "Amazon",
"screen_name": "amazon",
"location": "Seattle, Washington",
"description": "Official Twitter of http:\/\/t.co\/4rwjfdidk3. Contact #AmazonHelp for customer support.",
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"entities": {
"url": {
"urls": [
{
"url": "http:\/\/t.co\/Z2A4m7UeSv",
"expanded_url": "http:\/\/www.amazon.com",
"display_url": "amazon.com",
"indices": [
0,
22
]
}
]
},
"description": {
"urls": [
{
"url": "http:\/\/t.co\/4rwjfdidk3",
"expanded_url": "http:\/\/Amazon.com",
"display_url": "Amazon.com",
"indices": [
20,
42
]
}
]
}
},
"protected": false,
"followers_count": 2567418,
"friends_count": 157,
"listed_count": 13988,
"created_at": "Fri Feb 13 18:39:54 +0000 2009",
"favourites_count": 3092,
"utc_offset": -25200,
"time_zone": "Pacific Time (US & Canada)",
"geo_enabled": true,
"verified": true,
"statuses_count": 23791,
"lang": "en",
"contributors_enabled": false,
"is_translator": false,
"is_translation_enabled": false,
"profile_background_color": "9ACAF8",
"profile_background_image_url": "http:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_image_url_https": "https:\/\/pbs.twimg.com\/profile_background_images\/448506280982753280\/GZ6eb7ux.png",
"profile_background_tile": false,
"profile_image_url": "http:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_image_url_https": "https:\/\/pbs.twimg.com\/profile_images\/786252488223580160\/9-Lwv1sI_normal.jpg",
"profile_banner_url": "https:\/\/pbs.twimg.com\/profile_banners\/20793816\/1492450739",
"profile_link_color": "FF9900",
"profile_sidebar_border_color": "FFFFFF",
"profile_sidebar_fill_color": "FFFFFF",
"profile_text_color": "000000",
"profile_use_background_image": false,
"has_extended_profile": false,
"default_profile": false,
"default_profile_image": false,
"following": null,
"follow_request_sent": null,
"notifications": null,
"translator_type": "none"
},
"geo": null,
"coordinates": null,
"place": null,
"contributors": null,
"is_quote_status": false,
"retweet_count": 0,
"favorite_count": 1,
"favorited": false,
"retweeted": false,
"lang": "en"
}]

Error in sending Raw data with cURL in PHP

I have to send a request to an API. The reques should contain some data along with 4 header parameters. Teh Raw data that I want to send is the $raw_data.
The Error is : Internal Server Error
My Code is as follows :
<?php
function CurlSendPostRequest($url,$request="")
{
$raw_data='{
"job_id": null,
"collectionOnDelivery": false,
"invoice": null,
"collectionDate": "2015-01-30T09:00:00",
"consolidate": false,
"consignment": [{
"consignmentNumber": null,
"consignmentRef": null,
"parcels": [],
"collectionDetails": {
"contactDetails": {
"contactName": "My Contact",
"telephone": "0121 500 2500"
},
"address": {
"organisation": "GeoPostUK Ltd",
"countryCode": "GB",
"postcode": "B66 1BY",
"street": "Roebuck Lane",
"locality": "Smethwick",
"town": "Birmingham",
"county": "West Midlands"
}
},
"deliveryDetails": {
"contactDetails": {
"contactName": "My Contact",
"telephone": "0121 500 2500"
},
"address": {
"organisation": "GeoPostUK Ltd",
"countryCode": "GB",
"postcode": "B66 1BY",
"street": "Roebuck Lane",
"locality": "Smethwick",
"town": "Birmingham",
"county": "West Midlands"
},
"notificationDetails": {
"email": "my.email#geopostuk.com",
"mobile": "07921000001"
}
},
"networkCode": "2^12",
"numberOfParcels": 1,
"totalWeight": 5,
"shippingRef1": "My Ref 1",
"shippingRef2": "My Ref 2",
"shippingRef3": "My Ref 3",
"customsValue": null,
"deliveryInstructions": "Please deliver with neighbour",
"parcelDescription": "",
"liabilityValue": null,
"liability": false
}]
}';
// $authentication = base64_encode("USER:PASS");
$ch = curl_init($url);
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_POSTFIELDS => $raw_data,
// CURLOPT_FOLLOWLOCATION => false, // follow redirects
// CURLOPT_ENCODING => "utf-8", // handle all encodings
CURLOPT_AUTOREFERER => true, // set referer on redirect
// CURLOPT_CONNECTTIMEOUT => 20, // timeout on connect
// CURLOPT_TIMEOUT => 20, // timeout on response
CURLOPT_POST => 1, // i am sending post data
CURLOPT_POSTFIELDS => $request, // this are my post vars
// CURLOPT_SSL_VERIFYHOST => 0, // don't verify ssl
// CURLOPT_SSL_VERIFYPEER => false, //
// CURLOPT_VERBOSE => 1,
CURLOPT_HTTPHEADER => array(
"Accept: application/json",
"Content-Type: application/json",
"GEOClient: account/XX-ACC_NO-XX",
"GEOSession: XX-SESS_ID-XX"
)
);
curl_setopt_array($ch,$options);
$data = curl_exec($ch);
$curl_errno = curl_errno($ch);
$curl_error = curl_error($ch);
//echo $curl_errno;
//echo $curl_error;
print_r($data);
curl_close($ch);
return $data;
}
$url = "https://api.URL.com";
CurlSendPostRequest($url);
?>
A very silly mistake was done : I added a line
CURLOPT_POSTFIELDS => $raw_data,
and few lines below I added
CURLOPT_POSTFIELDS => $request,
My values for the raw Data are in $raw_data, thus $request was over-writing that.Just need to comment the line :
CURLOPT_POSTFIELDS => $request,
and it works great!

Categories