JSON write out with PHP [duplicate] - php

This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 3 years ago.
I have a JSON message, and I dont know How can I write out a part of json.
I tried:
{{$data[0]->items[0]}}
{{$data[0]->name}}
{{$data->items[0]-name}}
{{$data[0]->items}}
ect...
JSON message:
{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
}
]
}
EDIT:
This is the Controller
As you see $data array is decoded
It looks like your post is mostly code; please add some more details. omg
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
return view('clash', ['data' => $data]);

First you have to decode your JSON-String to a PHP-Array and then you can access it easily this way:
$json = '{
"items":[
{
"name":"Knight",
"id":26000000,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/jAj1Q5rclXxU9kVImGqSJxa4wEMfEhvwNQ_4jiGUuqg.png"
}
},
{
"name":"Archers",
"id":26000001,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/W4Hmp8MTSdXANN8KdblbtHwtsbt0o749BbxNqmJYfA8.png"
}
},
{
"name":"Goblins",
"id":26000002,
"maxLevel":13,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/X_DQUye_OaS3QN6VC9CPw05Fit7wvSm3XegXIXKP--0.png"
}
},
{
"name":"Giant",
"id":26000003,
"maxLevel":11,
"iconUrls":{
"medium":"https:\/\/api-assets.clashroyale.com\/cards\/300\/Axr4ox5_b7edmLsoHxBX3vmgijAIibuF6RImTbqLlXE.png"
}
}
]
}';
$array = json_decode( $json, true ); // we receive an associative array because the second parameter is true
echo $array['items'][0]['name'];
echo $array['items'][1]['id'];
Usage in for example:
$token = "token";
$url = "https://api.clashroyale.com/v1/cards";
$ch = curl_init($url);
$headr = array();
$headr[] = "Accept: application/json";
$headr[] = "Authorization: Bearer ".$token;
curl_setopt($ch, CURLOPT_HTTPHEADER, $headr);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$res = curl_exec($ch);
$data = json_decode($res, true);
curl_close($ch);
echo $data['items'][0]['name']; // echo the value of the key 'name' of the first element in items
echo $data['items'][1]['id']; // echo the value of the key 'id' of the second element in items
// you can also store them or do whatever you want
return view('clash', ['data' => $data]);
Or access the data in your view like this:
{{ $data['items'][0]['name'] }}
{{ $data['items'][0]['id'] }}

Related

Shopify GraphQL Error "Parse error on \":\" (COLON) at [2, 35]" With PHP

Greetings I have a problem with my GraphQL I don't know how to pass data to my GraphQL without getting
Error Message: "Parse error on ":" (COLON) at [2, 35]"
here is what I'm trying to pass product variant id data and get some response here is the example of what I'm trying to do and my function for graphql
$variantId = (isset($data->variantId) && !empty($data->variantId)) ? strip_tags($data->variantId) : "";
if(empty($variantId)){
$result['error'] = "Product id not specified!";
}
$query = array("query" => '{
productVariant(id: '. ($variantId) .') {
availableForSale
}
}');
$variants = shopify_gql_call($_SESSION['access_token'], $_SESSION['shop_name'], $query);
if( isset($variants['response']) && !empty($variants['response']) ){
$result[] = $variants['response'];
}else{
$result['error'] = "Variants not found!";
}
function shopify_gql_call($token, $shop, $query = array()) {
// Build URL
$url = "https://" . $shop . ".myshopify.com" . "/admin/api/".getenv('API_DATE')."/graphql.json";
// Configure cURL
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, TRUE);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, TRUE);
curl_setopt($curl, CURLOPT_MAXREDIRS, 3);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
// curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 3);
// curl_setopt($curl, CURLOPT_SSLVERSION, 3);
curl_setopt($curl, CURLOPT_USERAGENT, 'My New Shopify App v.1');
curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($curl, CURLOPT_TIMEOUT, 30);
// Setup headers
$request_headers[] = "";
$request_headers[] = "Content-Type: application/json";
if (!is_null($token)) $request_headers[] = "X-Shopify-Access-Token: " . $token;
curl_setopt($curl, CURLOPT_HTTPHEADER, $request_headers);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($query));
curl_setopt($curl, CURLOPT_POST, true);
// Send request to Shopify and capture any errors
$response = curl_exec($curl);
$error_number = curl_errno($curl);
$error_message = curl_error($curl);
// Close cURL to be nice
curl_close($curl);
// Return an error is cURL has a problem
if ($error_number) {
return $error_message;
} else {
// No error, return Shopify's response by parsing out the body and the headers
$response = preg_split("/\r\n\r\n|\n\n|\r\r/", $response, 2);
// Convert headers into an array
$headers = array();
$header_data = explode("\n",$response[0]);
$headers['status'] = $header_data[0]; // Does not contain a key, have to explicitly set
array_shift($header_data); // Remove status, we've already set it above
foreach($header_data as $part) {
$h = explode(":", $part, 2);
$headers[trim($h[0])] = trim($h[1]);
}
// Return headers and Shopify's response
return array('headers' => $headers, 'response' => $response[1]);
}
}
I strongly suggest the use of https://packagist.org/packages/shopify/shopify-api instead of implementing your own function/http requests.
Your query should be something like this
query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}
and then you submit the ID as part of another entry of the array, check the example below:
$query = [
"query" =>
'query anynamehere($id: ID!){
productVariant(id:$id){
availableForSale
}
}',
"variables" => [
'id' => $variantId
]
];
You should never concatenate the values as part of the query string (unless you want to deal with a lot of injection issues). Check more info about variables here https://graphql.org/learn/queries/

Remove item from JSON returned from API

I'm new to PHP and have some trouble trying to delete an item from some data returned by an API
function getData()
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
curl_setopt($ch, CURLOPT_POSTFIELDS, "");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',));
$data = curl_exec($ch);
echo $data;
exit();
}
Here is the JSON data, I want to remove the item with Id 11, how can I do this?
{
"Data": [
{
"Id": 11,
"Name": "Name1"
},
{
"Id": 12,
"Name": "Name2"
}
]
}
Decode the data.
Remove the item from the array.
Optionally encode it again as string if needed.
$dataArray = json_decode($data, true);
foreach ($dataArray['Data'] as $key => $item) {
if ($item['Id'] === 11) {
unset($dataArray['Data'][$key]);
}
}
$data = json_encode($dataArray);
it will work
$dataArray = json_decode($data, true);
$dataArray['Data'] = array_filter($dataArray['Data'], function($el){return $el["Id"]<>11;});
$data = json_encode($dataArray);
One way is to re-index by Id and unset it:
$array = array_column(json_decode($data, true)['Data'], null, 'Id'));
unset($array[11]);
Now $array is indexed by Id. If you want to reset it, then:
$array = array_values($array);

Decode returns Int php curl JSON

I have a CURL that returns the following:
{"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}
I am trying to get the amount JSON variable into a PHP variable. I am using the following attempts:
$result=curl_exec($ch);
//1
var_dump(json_decode($result));
//2
var_dump(json_decode($result, true));
//3
$data = json_decode($result[0]->data,true);
The response of the previous var_dumps are
//1
/home/usbanktech/public_html/bitcoin2.php:24:int 1
//2
/home/usbanktech/public_html/bitcoin2.php:26:int 1
//3
$data attempt returns nothing
Trying to get "amount":"9342.29" into a php like $amount.
Full code:
// Generated by curl-to-PHP: http://incarnate.github.io/curl-to-php/
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.coinbase.com/v2/prices/BTC-USD/buy");
//curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"name\": \"New receive address\"}");
$headers = array();
$headers[] = "Content-Type: application/json";
$headers[] = "Authorization: Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c";
//$headers[] = "CB-ACCESS-KEY: <your api key>";
//$headers[] = "CB-ACCESS-SIGN: <the user generated message signature>";
//$headers[] = "CB-ACCESS-TIMESTAMP: <a timestamp for your request>";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result=curl_exec($ch);
// Closing
curl_close($ch);
$json = $result;
$array = json_decode($json,1);
$amount = $array['data']['amount'];
echo $amount;
You need to set this to true in order to get a json:
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
Otherwise, you will get an integer as a return value.
How about this decoding as an array and grab the amount value?
<?php
$json = ' {"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}';
$array = json_decode($json,1);
$amount = $array['data']['amount'];
echo $amount;
?>
DEMO: https://3v4l.org/RD6K9
OR with extract()
<?php
$json = ' {"data":{"base":"BTC","currency":"USD","amount":"9342.29"}}';
$array = json_decode($json,1);
extract($array['data']);
echo $amount;
?>
DEMO: https://3v4l.org/n2OCR

sending multidimensional array with curl in json format

I am trying to post data using curl to a api, it has to be in JSON.
Now I have an multidimensional array that i need to pass along with the post. But i keep getting the same error all over, and i can not figure out why.
I've tried every possible way I could imagine.
This is the example that i need to send to the API:
POST /orders/ HTTP/1.1
Authorization: Basic aHVudGVyMjo=
Content-Type: application/json
{
"currency": "EUR",
"amount": 99,
"return_url": "http://www.example.com/",
"transactions": [
{
"payment_method": "ideal",
"payment_method_details": {
"issuer_id": "INGBNL2A"
}
}
]
}
So my array I made like this:
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"]["payment_method"] = "ideal";
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = "INGBNL2A";
Then the follinw i do is converting the array to a JSON string by this code:
$data_string = json_encode($post_fields);
So far is everything OK, but then i am going to post the data to the API by using the following code:
$url = "https://api.kassacompleet.nl/v1/orders/";
$curl_header = array();
$curl_header[] = "Authorization: Basic ".base64_encode("$auth_code:");
$curl_header[] = "Content-type: application/json";
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_header);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 180);
curl_setopt($ch, CURLOPT_TIMEOUT, 180);
$output = curl_exec($ch);
curl_close($ch);
print_r($output);
And this always results in an error that looks as the following:
{ "error": { "status": 400, "type": "", "value": "{u'payment_method': u'ideal', u'payment_method_details': {u'issuer_id': u'INGBNL2A'}} is not of type u'array'" } }
Could someone tell me where it comes from and what I am doing wrong?
Is it the format of the array or what is it?
From checking the API documentaion
It looks like transactions should be an array.
$post_fields = array();
$post_fields["currency"] = "EUR";
$post_fields["amount"] = 99;
$post_fields["return_url"] = "http://website_url.nl/return_page/";
$post_fields["transactions"][0]["payment_method"] = "ideal";
$post_fields["transactions"][1]["payment_method_details"]["issuer_id"] = "INGBNL2A";
echo '<pre>'.json_encode($post_fields).'</pre>';
/* outputs...
{
"currency":"EUR",
"amount":99,
"return_url":"http:\/\/website_url.nl\/return_page\/",
"transactions":[
{
"payment_method":"ideal",
"payment_method_details":{
"issuer_id":"INGBNL2A"
}
}
]
}
*/
I suggest that param "issuer_id" should be an array, in that case try
...
$post_fields["transactions"]["payment_method_details"]["issuer_id"] = array("INGBNL2A");
...

how to convert command line curl to php curl

I need to convert this command line cURL into a php cURL and echo the result
curl -H "Content-Type: application/json" -d '{ "code":"<code>", "client_id": "<client_id>", "client_secret": "<client_secret>"}' https://www.example.com/oauth/access_token
how can this be done?
Try this simple approach:
$data = array("code"=>"123", "client_id"=> "123", "client_secret"=> "123");
$data_string = json_encode($data);
$ch = curl_init('https://www.example.com/oauth/access_token');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json',
'Content-Length: ' . strlen($data_string))
);
$result = curl_exec($ch);
Replace 123 with your values. Here is the manual for curl_setopt()
Something like this should work, assuming you need to POST the data to the URL:
<?php
// URL that the data will be POSTed to
$curl_url = 'https://www.example.com/oauth/access_token';
// Convert the data into an array
$curl_data_arr = array('{ "code":"<code>", "client_id": "<client_id>", "client_secret": "<client_secret>"}');
// Prepare to post as an array
$curl_post_fields = array();
foreach ($curl_data_arr as $key => $value) {
// Assuming you need the values url encoded, this is an easy way
$curl_post_fields[] = $key . '=' . urlencode($value);
}
$curl_header = array('Content-Type: application/json');
$curl_array = array(
CURLOPT_URL => $curl_url,
CURLOPT_HTTPHEADER => $curl_header,
CURLOPT_POSTFIELDS => implode('&', $curl_post_fields),
CURLOPT_POST => TRUE,
CURLOPT_RETURNTRANSFER => TRUE,
);
// Initialize cURL
$curl = curl_init();
// Tell cURL to use the array of options we just set up
curl_setopt_array($curl, $curl_array);
// Assign the result to $data
$data = curl_exec($curl);
// Empty variable (at first) to avoid errors being displayed
$result = '';
// Check for errors
if ($error = curl_error($curl)) {
// If there's an error, assign its value to $result
$result = $error;
}
curl_close($curl);
// If there's no errors...
if (empty($error)) {
// ... instead assign the value of $data to $result
$result = $data;
}
echo $result;

Categories