This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I tried to connect Coinmarketcap's API using PHP curl to take out the live bitcoin price out of it as a practice. The point is that the output it gives is way too confusing that I have got no idea about how should I take the "price" out of it. There were some similar questions around but unfortunately, the responses didn't help me. So I was wondering how is it possible to take the price of bitcoin out of the return given by API? It seems like I'm misunderstanding arrays and objects since I'm still a newbie.
This is what "die and dump" returns:
#data: array:1 [▼
"response" => """
{
"status": {
"timestamp": "2019-04-15T14:03:35.573Z",
"error_code": 0,
"error_message": null,
"elapsed": 5,
"credit_count": 1
},
"data": [
{
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"slug": "bitcoin",
"circulating_supply": 17646787,
"total_supply": 17646787,
"max_supply": 21000000,
"date_added": "2013-04-28T00:00:00.000Z",
"num_market_pairs": 7253,
"tags": [
"mineable"
],
"platform": null,
"cmc_rank": 1,
"last_updated": "2019-04-15T14:02:29.000Z",
"quote": {
"USD": {
"price": 5166.87433557,
"volume_24h": 11238888046.6075,
"percent_change_1h": 0.0140845,
"percent_change_24h": 1.39641,
"percent_change_7d": -0.981349,
"market_cap": 91178730855.57031,
"last_updated": "2019-04-15T14:02:29.000Z"
}
}
}
]
}
"""
]
Here is the code which requests from API:
function apiGet($url)
{
$parameters = [
'start' => '1',
'limit' => '3',
];
$query = http_build_query($parameters);
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "$url",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_TIMEOUT => 30000,
CURLOPT_POST => true,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_HTTPHEADER => array(
'Content-Type: application/json',
'Accept-Encoding: deflate, gzip',
'X-CMC_PRO_API_KEY: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
),
)
);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
print_r(json_decode($response));
}
return view('price', compact('response'));
}
$parameters = [
'start' => '1',
'limit' => '1',
];
$query = http_build_query($parameters);
$btc = new \App\Http\Controllers\CoinsController();
$result = $btc->apiGet('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'."?".$query);
dd($result);
That's a nested key value array that contains a json string. You can get the price like this:
$price = json_decode($result['response'])->data[0]->quote->USD->price;
Also for your knowledge. You can use the Arr::get() helper provided by Laravel. See docs:
use \Illuminate\Support\Arr;
...
$data = json_decode($result['response'], true);
$price = Arr::get($data, 'data.0.quote.USD.price');
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 have the following json created dynamically using php variables and it gives me:
{"message":"invalid json"}
Code:
$json = '{
"sex": "'.$gender.'",
"age": '.$age.',
"evidence": [
{"id": "'.$symptom_id1.'", "choice_id": "present", "initial": true},
{"id": "'.$symptom_id2.'", "choice_id": "present", "initial": true},
{"id": "p_7", "choice_id": "'.$test1.'"},
{"id": "p_8", "choice_id": "'.$test2.'"},
{"id": "p_9", "choice_id": "'.$test3.'"},
{"id": "p_10", "choice_id": "'.$test4.'"},
{"id": "p_28", "choice_id": "'.$test5.'"},
{"id": "'.$location.'", "choice_id": "present"}
],
"extras": {
"disable_groups": true
}
}';
$ch = curl_init('https://api.infermedica.com/v2/diagnosis');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($json),
'app_id: '. APP_ID,
'app_key: '. APP_KEY,
'Interview-Id: '.$interview_id,
'User-Id: '. $hasheduser_id
]);
$result = curl_exec($ch);
echo '<pre>';
print_r( $result );
echo '</pre>';
Hard coding the values in place of variables works fine. Being a newbie, I am unable to understand the reason why it is not well formed.
Help requested.
You should never try and create valid JSON on your own, it will only lead to security issues and bugs, instead use a data structure and pass it to json_encode.
Example data structure for your use:
$to_json = [
'sex' => $gender,
'age' => $age,
'evidence' => [
['id' => $symptom_id1, 'choice_id' => 'present', 'initial' => true],
['id' => $symptom_id2, 'choice_id' => 'present', 'initial' => true],
['id' => 'p_7', 'choice_id' => $test_1],
['id' => 'p_8', 'choice_id' => $test_2],
['id' => 'p_9', 'choice_id' => $test_3],
['id' => 'p_10', 'choice_id' => $test_4],
['id' => 'p_28', 'choice_id' => $test_5],
['id' => $location, 'choice_id' => 'present'],
],
'extras' => [
'disabled_groups' => true
],
];
Then encode it:
$json = json_encode($jo_json);
Hope this helps.
Your JSON is invalid due to a typo on the 2nd line of your variable.
"age": '.$age.',
should be
"age": "'.$age.'",
Or what would be better
"age": "$age",
But the best way to accomplish what you are attempting to do would be to create a PHP array, and pass this to json_encode.
$array = ['hello, i am a key'=>'i am some data'];
var_dump(json_encode($array));
I am using magento 2 api for assigning product link like related or crosssell
using api /V1/products/{sku}/links
Here is My Sample Code
<?php
error_reporting(E_ALL);
define('mag_apiurl',"http://www.mywebsite.com/rest/V1/");
define('tn_webshopKey',"myshowpkey");
$sku1 = "sku1";
$sku2 = "sku2";
$productData = array(
"items" => array(
"sku" => $sku1,
"linkType" => 'related',
"linkedProductSku" => $sku2,
"linkedProductType" => "simple",
"position" => 0
)
);
$headers = array("Content-Type:application/json","Authorization: Bearer ".tn_webshopKey);
$requestUrl= mag_apiurl.'products/'.$sku1.'/links';
$ch = curl_init($requestUrl);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($productData));
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
echo $returnProductDetails = curl_exec($ch);
?>
But Every time i run the script its
response
{"message":"%fieldName is required filed.","parameters":{"fieldName":"linkType"}}
But the link type 'related' is already defined in my data (productData)
Does anyone knows the solution or related link which helps :)
Could you try setting "linkType" to 1 instead of "related"
$linkTypes = ['related' => 1, 'upsell' => 4, 'crosssell' => 5, 'associated' => 3];
Sorry Its my fault i'am reading the swagger api documentation for enterprise version of magento-2.2.* but i am working on magento-2.1.*
Actual Code Should be
$productData = array(
"items" => array(
array(
"sku" => $sku1,
"link_type" => 'related',
"linked_product_sku" => $sku2,
"linked_product_type" => "simple",
"position" => 0
)
)
);
/*
THE JOSN FORMAT START
{
"items": [
{
"sku": "string",
"link_type": "string",
"linked_product_sku": "string",
"linked_product_type": "string",
"position": 0,
"extension_attributes": {
"qty": 0
}
}
]
}
***************END************/
There are some differences ive noticed between those documentation that each document have different model schema declaration like some has snake_case and on other hand some has camelCase so do not begin confused between the documentation of swagger and select appropriate version of document for each store
Im creating a simple web application in php that consume the adaptivePayments/Pay Api of paypal, I made some test using POSTMAN and everything works fine, I make the initial request and I get my payKey, also with this payKey I can check the status of the transaction using the /AdaptivePayments/PaymentDetails Api, the problem is when I try to make the request via php code:
$endpoint = 'https://svcs.sandbox.paypal.com/AdaptivePayments/Pay';
$payload['actionType'] = "PAY";
$payload['clientDetails']['applicationId'] = "APP-80W284485P519543T";
$payload['clientDetails']['ipAddress'] = "xxx.xxx.xxx.xxx";
$payload['currencyCode'] = "USD";
$payload['feesPayer'] = "EACHRECEIVER";
$payload['memo'] = "Transaction";
$payload['receiverList']['receiver'] = $receivers;
$payload['requestEnvelope']['errorLanguage'] = "en_US";
$payload['returnUrl'] = "URL";
$payload['cancelUrl'] = "URL";
$json = json_encode($payload);
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X-PAYPAL-SECURITY-USERID: ACCOUNT',
'X-PAYPAL-SECURITY-PASSWORD: PASSWORD',
'X-PAYPAL-SECURITY-SIGNATURE: SIGNATURE',
'X-PAYPAL-REQUEST-DATA-FORMAT: JSON',
'X-PAYPAL-RESPONSE-DATA-FORMAT: JSON',
'X-PAYPAL-APPLICATION-ID: APP-80W284485P519543T',
'Content-Type: application/json',
'Content-Length: ' . strlen($json)
));
$result = curl_exec($ch);
$receivers is a PHP array that contain information about emails and payment amounts, something like this:
Array
(
[0] => Array
(
[amount] => 19.8
[email] => client2-ubs#gmail.com
[primary] =>
)
[1] => Array
(
[amount] => 20.7
[email] => client1-ubs#gmail.com
[primary] =>
)
[2] => Array
(
[amount] => 45
[email] => store-ubs#gmail.com
[primary] => 1
)
)
I dont get any error, I even get the payKey which I use to create the html button so the user can pay for his goods, the problem is when I check the payment status /AdaptivePayments/PaymentDetails, Im getting:
{
"responseEnvelope": {
"timestamp": "2015-08-06T23:59:23.075-07:00",
"ack": "Success",
"correlationId": "bab22ca0bd887",
"build": "17603431"
},
"cancelUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"currencyCode": "USD",
"paymentInfoList": null,
"returnUrl": "https://23410a33.ngrok.com/universal-bank-of-souls/",
"status": "CREATED",
"payKey": "AP-8ML17897XK803351A",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"sender": {
"useCredentials": "false"
}
}
for some strange reason paymentInfoList is null, so the user see an error (transaction error) at the moment of click the paypal button.
As I said before, If i made the transaction using POSTMAN and then check the status I get a correct response:
{
"responseEnvelope": {
"timestamp": "2015-08-07T00:14:08.510-07:00",
"ack": "Success",
"correlationId": "b9049ba0d4cf1",
"build": "17603431"
},
"cancelUrl": "URL",
"currencyCode": "USD",
"memo": "Bank of souls payment",
"paymentInfoList": {
"paymentInfo": [
{
"receiver": {
"amount": "123.30",
"email": "client2-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "SLKM4ZQ5FMSHG"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "510.30",
"email": "client1-ubs#gmail.com",
"primary": "false",
"paymentType": "SERVICE",
"accountId": "8PUDR7LSRS4MJ"
},
"pendingRefund": "false"
},
{
"receiver": {
"amount": "704.00",
"email": "store-ubs#gmail.com",
"primary": "true",
"paymentType": "SERVICE",
"accountId": "E29BAQX7C7P3N"
},
"pendingRefund": "false"
}
]
},
"returnUrl": "URL",
"status": "CREATED",
"payKey": "AP-9MU4806743660523S",
"actionType": "PAY",
"feesPayer": "EACHRECEIVER",
"reverseAllParallelPaymentsOnError": "false",
"sender": {
"useCredentials": "false"
}
}
(paymentInfoList actually contains a json object with the goods, but this is doing the request manually using POSTMAN)
Could this be a PHP issue? some ideas to debug the curl connection will help me a lot.
PD: I have been debuging this the whole day, I even print_r the $json variable (i get the json format) and copy / paste directly in postman and its works, but for some reason the same request using curl is not sending the $receivers information.
Solved, I was making the requests (create the order and the request order information) using two different api credentials, also, it seems that paypal hide the order goods when receiving api credentials different than the originals, however still showing the state of the order (CREATE, COMPLETED, etc)
I call the Google MAP Geolocation API in PHP, to get the location by the cellTower information. However, when I change any of the cellTower information, I always get the same results: { "location": { "lat": 52.519171, "lng": 13.406091 }, "accuracy": 18000.0 }.
Here is my PHP script, could anyone help to check where is the problem? Thank you.
<?php
// The data to Google API
$JsonData = array(
'CellTowers' => array (
'cellId' => 42,
'locationAreaCode' => 415,
'mobileCountryCode' => 310,
'mobileNetworkCode' => 410
));
// Create the context for the request
$context = stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => "Content-Type: application/json\r\n",
'content' => json_encode($JsonData)
)
));
// Send the request
$response = file_get_contents('https://www.googleapis.com/geolocation/v1/geolocate?key=', FALSE, $context);
// Check for errors
if($response === FALSE){
die('Error');
}
echo $response;
?>
The problem is the JSON data, it works when changed the $cellData to following:
$cellData = array(
'cellTowers' => array (
array ('cellId' => 42,
'locationAreaCode' => 415,
'mobileCountryCode' => 310,
'mobileNetworkCode' => 410)
));