I'm Having issues grabbing values in a multi level array.
This is my JSON I am grabbing with CURL and putting into a variable.
{
"id": 454626,
"results": [
{
"iso_3166_1": "SK",
"release_dates": [
{
"certification": "U",
"iso_639_1": "sk",
"note": "",
"release_date": "2020-02-20T00:00:00.000Z",
"type": 3
}
]
},
{
"iso_3166_1": "DE",
"release_dates": [
{
"certification": "6",
"iso_639_1": "",
"note": "",
"release_date": "2020-02-13T00:00:00.000Z",
"type": 3
}
]
},
{
"iso_3166_1": "TW",
"release_dates": [
{
"certification": "G",
"iso_639_1": "",
"note": "",
"release_date": "2020-02-21T00:00:00.000Z",
"type": 3
}
]
}
]
}
This is my PHP code that I'm having issues with.
$id_tmdb = $row[id_tmdb];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://api.themoviedb.org/3/movie/$id_tmdb/release_dates?api_key=API-KEY",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET"
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
$result = json_decode($response, true);
foreach($result[results][release_dates] as $key=>$val){
echo "$val[release_date]";
}
I'm trying to get the release_date but it just shows blank.
I have another page that is formatted the same way so I am unsure why it isn't working.... Thank you for all your help.
Your $result['results'] value is also an array and you need to iterate over that as well as the release_dates array:
foreach($result['results'] as $results) {
foreach ($results['release_dates'] as $val){
echo "$val[release_date]\n";
}
}
Output (for the sample JSON provided):
2020-02-20T00:00:00.000Z
2020-02-13T00:00:00.000Z
2020-02-21T00:00:00.000Z
Demo on 3v4l.org
This should get you there:
foreach($result['results'] as $res){
echo $res['release_dates'][0]['release_date']."\n";
}
3v4l link
On a side-note, I put the array keys in quotes to prevent php warnings.
Related
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
Given this generated code from postman, $body->append(); from POSTMAN API, how to replace it with variables?
how to replace the CURLOPT_POSTFIELDS with php variables? so it can be filled with dynamic variable
what is the best practices to do it?
thank you
<?php
$json = '{
"RateRequest": {
"ClientDetails" : null,
"RequestedShipment": {
"DropOffType": "REQUEST_COURIER",
"ShipTimestamp": "2020-08-25T11:00:00GMT+02:00",
"UnitOfMeasurement": "SI",
"Content": "NON_DOCUMENTS",
"PaymentInfo": "DAP",
"NextBusinessDay": "Y",
"Account": "54xxxxxx",
"Ship": {
"Shipper": {
"City": "city",
"PostalCode": 123456,
"CountryCode": "ID"
},
"Recipient" : {
"City" : "canberra",
"PostalCode" : 2601,
"CountryCode" : "AU"
}
},
"Packages": {
"RequestedPackages": {
"#number": "1",
"Weight": {
"Value": 8.82
},
"Dimensions": {
"Length": 4.33,
"Width": 4.33,
"Height": 4.33
}
}
}
}
}
}';
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://wsbexpress.dhl.com/rest/sndpt/RateRequest",
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 => $json,
CURLOPT_HTTPHEADER => array(
"Authorization: Basic YmF0dWxheWFuZ3NJRDpKXjBlUEA2dkQhM2Y=",
"Content-Type: application/json",
"Cookie: BIGipServer~WSB~pl_wsb-express-cbj.dhl.com_443=293349575.64288.0000"
),
));
$response = curl_exec($curl);
curl_close($curl);
echo $response;
json_decode the string into an array
modify the values as needed
set that data for CURLOPT_POSTFIELDS
Something like this
$json = '{
"RateRequest": {
"ClientDetails" : null,
"RequestedShipment": {
"DropOffType": "REQUEST_COURIER",
"ShipTimestamp": "2020-08-25T11:00:00GMT+02:00",
"UnitOfMeasurement": "SI",
"Content": "NON_DOCUMENTS",
"PaymentInfo": "DAP",
"NextBusinessDay": "Y",
"Account": "54xxxxxx",
"Ship": {
"Shipper": {
"City": "city",
"PostalCode": 123456,
"CountryCode": "ID"
},
"Recipient" : {
"City" : "canberra",
"PostalCode" : 2601,
"CountryCode" : "AU"
}
},
"Packages": {
"RequestedPackages": {
"#number": "1",
"Weight": {
"Value": 8.82
},
"Dimensions": {
"Length": 4.33,
"Width": 4.33,
"Height": 4.33
}
}
}
}
}
}';
$data = json_decode($json, true);
if (isset($data['RateRequest']['RequestedShipment']['DropOffType'])) {
$data['RateRequest']['RequestedShipment']['DropOffType'] = 'some new value';
}
//... later in your curl call...
CURLOPT_POSTFIELDS => $data,
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);
i am trying to get Youtube channel data with that api
https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id={ Channel Id }&key={ API }
I used that code to fetch the data
if( $_SERVER[ 'REQUEST_METHOD' ] == 'GET' && !empty( $_GET ) ){
$channel_id = $_GET[ 'channel_id' ];
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => "https://www.googleapis.com/youtube/v3/channels?part=snippet,contentDetails,statistics&id=". $channel_id ."&key=AIzaSyCKAnI41bI4UGDJgYUcwrhrIfnjoD3uirM",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_POSTFIELDS => "",
CURLOPT_HTTPHEADER => array(
"content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW"
),
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
}
?>
<form id="channelIdForm" action="<?php $_SERVER['PHP_SELF']; ?>" method="get">
<input type="text" placeholder="Type channel id" name="channel_id" id="channelId" />
<button type="submit">Get data</button>
</form>
And it appeared like that
{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] }
Then i tried to convert that json to an array to pick what i want from it with index
So i tried that instead of $response
$json = $response;
$arr = json_decode($json, true);
$row = array_reduce($arr['items'], function($c, $v){
$c[ key($v) ] = current($v);
return $c;
}, array());
print_r( $row );
I expected to see all the indexes below item but the result was
Array ( [kind] => youtube#channel )
It show just kind i don't know what the problem with so if any one can help i will be appreciated!!
The array_reduce function reduces an array to a single value. But it appears you are interested in multiple key/value pairs. Since json_decode($json, true); already provides you with an associated array you can retrieve specific keys via their names. Example:
$arr = json_decode($response, true);
$newArray = [];
$requiredKeys = ['kind','etag'];
foreach ($requiredKeys as $key){
$newArray[$key] = $arr[$key];
}
It is a very-multi-dimensional array.
Here's some code that prints the contents of an array. If the value it is going to print is an array, it calls itself again. You'll see it puts out Printing $json_arr[items[0][statistics] : followed by a bunch of key->value pairs, so you can find the state you want and you'll know what the parent array(s) are.
<?php
$json='{ "kind": "youtube#channelListResponse", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/pss5QFB6saoevVwzX-8y6f1U75E\"", "pageInfo": { "totalResults": 1, "resultsPerPage": 1 }, "items": [ { "kind": "youtube#channel", "etag": "\"DuHzAJ-eQIiCIp7p4ldoVcVAOeY/gPFze0Hh7eRu9O5tXiTBVyvCwa8\"", "id": "UC4QYTjhWMxiC6UwvKLVkDDA", "snippet": { "title": "حفيد برايز حفيد برايز", "description": "", "publishedAt": "2018-04-01T17:18:31.000Z", "thumbnails": { "default": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s88-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 88, "height": 88 }, "medium": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s240-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 240, "height": 240 }, "high": { "url": "https://yt3.ggpht.com/-wuTRH4WK_UA/AAAAAAAAAAI/AAAAAAAAAAA/ms_Qpu4ekLk/s800-c-k-no-mo-rj-c0xffffff/photo.jpg", "width": 800, "height": 800 } }, "localized": { "title": "حفيد برايز حفيد برايز", "description": "" } }, "contentDetails": { "relatedPlaylists": { "uploads": "UU4QYTjhWMxiC6UwvKLVkDDA", "watchHistory": "HL", "watchLater": "WL" } }, "statistics": { "viewCount": "830460", "commentCount": "0", "subscriberCount": "3741", "hiddenSubscriberCount": false, "videoCount": "19" } } ] } ';
$json_arr=json_decode($json,true);
function print_array($prefix,$arr){
print("printing ".$prefix." :\n");
foreach($arr as $k=>$v){
if(is_array($v)){
print_array($prefix."[".$k."]",$v);
}else{
print("key: ".$k." value:".$v." \n");
}
}
return;
}
print_array("\$json_arr",$json_arr);
?>
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!