This question already has answers here:
Multidimensional array: check if key exists
(3 answers)
Closed 3 months ago.
I need to find if a string exists in JSON Kraken.com retrieved file:
I get it this way:
$sURL = "https://api.kraken.com/0/public/OHLC?pair=ETHAED&interval=5&since=". strtotime("-1 day");
$ch = curl_init();
$config['useragent'] = 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:17.0) Gecko/20100101 Firefox/17.0';
curl_setopt($ch, CURLOPT_USERAGENT, $config['useragent']);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $sURL);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
Sometimes pairs names differ from URL string and JSON (i.e. I can write LTCEUR but in JSON I see LTCZEUR
So I need to check if the string does exists in the $obj
$sName = "ETHAED";
print_r($obj);
if (in_array($sName,$obj)){
echo("Found ".$sName."<br>");
}else{
echo("NOT FOUND"."<br>");
}
but this doesn't work.
if I do a print_r() I can clearly see the pair name, but can't verify it.
Any suggestion?
Kraken.com JSON is not standard so I can't easily retrieve the name of the PAIR, I tried all possible combinations of $obj["result"][$sName] but without result.
Example:
https://api.kraken.com/0/public/OHLC?pair=LTCUSD
Here pair is LTCUSD
But on Json:
{"error":[],"result":{"XLTCZUSD":[[1669197540,"78.74","78.74","78.58","78.59","78.59","23.82168114",8]
Something is wrong with your comparison.
in_array($sName,$obj)
Should be:
is_array($obj['result'][$sName] ?? null)
Caveat: Read that carefully; it's now is instead of in.
Or, if you don't care if it's null, a string, or non-array:
array_key_exists($obj['result'], $sName)
Detailed explanation
in_array($sName,$obj) is checking if $sName matches (== equality) any of the elements in the first level of your array.
Since the first level of the array looks like this (pseudocode here):
error => []
result => [
XLTCZUSD => [...]
last: 123456
]
Since 'ETHAED' is neither [] nor is it [XLTCZUSD => [...],last: 123456] it doesn't match anything.
Yes it works perfectly.
Just a little correction on format:
if (array_key_exists($sName, $obj['result'])){
echo("FOUND ".$sName."<br>");
}else{
echo("ERROR ".$sName."<br>");
}
Related
I'm new to StackOverflow, so I apologize if I'm not formatting this correctly. I'm using the GitHub API and my goal is to get a list of a user's repositories in a dropdown form that they can select from.
Let's say the repository list URL is https://api.github.com/users/MY_GITHUB_USERNAME/repos (The way I sat things up I can get the repo URL by doing $userdata->repos_url). When I use the following:
$curl1 = curl_init();
curl_setopt($curl1, CURLOPT_URL, $userdata->repos_url);
curl_setopt($curl1, CURLOPT_HEADER, 0);
curl_setopt($curl1, CURLOPT_HTTPHEADER, array(
'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth'
));
curl_setopt($curl1,CURLOPT_USERAGENT,'User-Agent: MY_WEBSITE_HERE Addon Developer OAuth');
curl_setopt($curl1, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl1, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl1, CURLOPT_SSL_VERIFYHOST, 0);
$cont1 = curl_exec($curl1);
curl_close($cont1);
echo $cont1;
It responds with the following:
[
{
(information I don't need)
"full_name": "github-username/this-is-what-i-want",
(information I don't need)
}
]
I only have one repository at the moment. What I want to do is make a code that echos only the full_name and if there's more than one array echo each one. (All arrays will have full_name.)
Does anyone know how I could do this?
Decode it to an array, then loop through the arrays until you get to what you want:
$data=json_decode($cont1, true); <~~~ tells php to decode the JSON into an array
$results=$data['FirstArray']['SecondArray']['NumResultsReturned']; <~~ most JSON's have a value showing how many arrays got sent back to you in the results. You didn't give a true data example as a reply, so can't give exacts on these fields for you.
I need to get the [result]->[data]->[id]->xx informations out of extern item-API json arrays. I want to save them in a mysql table (items).
Example url to the first json array:
https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[1,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ
You see the [1,] in the url. This is the minimum item ID from wehere I want to start fetching.
The maximum items one json array url can show is 1000. The API has over 170.000 items for which I need their particular [data] [id]. The API calls are limited to 100 per second and 36.000 per hour.
My idea is to get the last [data] [id] value from the current array. Then in the next loop I add 1 to the last arrays´ [data] [id] value as the starting point for the next loop. And so on.
In the example url the last item id is 2429. So in the next loop 2430 would be the starting point.
https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[2430,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ
This is my code. I don´t know how to loop this and if this would be possible to do. Maybe there is an easier solutiuon.
//**Decode JSON in PHP ARRAY**//
function getSslPage($url, $userAgent)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_USERAGENT, $userAgent);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_REFERER, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
return json_decode($result, true);
}
$userAgent = 'Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0';
//**GET the [DATA] [ID] value of the last KEY in the CURRENT array**//
$all_values = array_values($data['results']);
$last_value = end($all_values);
//**In the next LOOP the [DATA] [ID] VALUE should be +1 as the new starting point**//
$startingItem = $last_value['data']['id'] + 1;
$url = "https://eu.api.blizzard.com/data/wow/search/item?namespace=static-eu&orderby=id&_pageSize=1000&id=[$startingItem,]&_page=1&locale=de_DE&access_token=USPqoKWmdURvO1mmDeW5vRghI5dojO13XZ";
$data = getSslPage($url, $userAgent);
//** INSERT in database **//
foreach ($data['results'] as $entry) {
$sqle= "REPLACE INTO `items`
(`id`)
VALUES
('{$entry['data']['id']}')";
}
If you're using PHP version > 7.3 you can retrieve the last index key using array_key_last()
By the way you are retrieving your last key using
end($all_values).
Watch out for the comma (,) at the end of that index, you should trim your index string to contain only numbers, try with
$newkey = trim($key, ',')
Then you can retrieve its int value with intval()
$intnewkey = intval($newkey).
Now you will be able to increment your index with
$intnewkey++;,
return back to string with strval()
$newIndex = strval($intnewkey)
and then append again the comma to your new value for you API Call:
$newIndexForAPI = $newIndex . ','
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I'm using PHP to get a JSON response from a website and then process the response using json_decode. This is my PHP code:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,"https://api.checkwx.com/taf/LLBG/?format=json");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$vars); //Post Fields
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$headers = [
'X-API-Key: 555555555'
];
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
curl_close ($ch);
$json=json_decode($response,true);
$fulltaf = $json['status']['success']['data']['icao'];
This doesn't work.
This is the JSON data returned to be processed by json_decode:
{
"status": "success",
"data": [
{
"icao": "KPIE",
"observed": "07-03-2017 # 14:20Z",
"raw_text": "KPIE 071353Z 13017G23KT 10SM CLR 21\/13 A3031 RMK AO2 SLP262 T02060128",
"wind_degrees": 130,
}
]
}
You don't specify what didn't work?
First problem is that your JSON has a syntax error. I tried to validate your JSON using http://jsonlint.com and it flagged an extra comma after the 130 for wind_degrees. Check that actual response doesn't have that comma. The JSON won't parse properly with the extra comma.
The next problem is that data is an array (because its data is enclosed in brackets). In this example the array only has one element, [0], therefore to access icao you need to reference it as I show below.
My guess is that the following line didn't work correctly:
$fulltaf = $json['status']['success']['data']['icao'];
Based on the JSON you listed, this line should be the following if you want to retrieve the icao member of data.
$fulltaf = $json['data'][0]['icao'];
The following reference should return 'success' if you want to test for a successful response.
$json['status']
I tried implementing the following PHP code to POST JSON via PHP: cURL (SOME FORCE.COM WEBSITE is a tag that signifies the URL that I want to POST):
$url = "<SOME FORCE.COM WEBSITE>";
$data =
'application' =>
array
(
'isTest' => FALSE,
key => value,
key => value,
key => value,
...
)
$ch = curl_init($url);
$data_string = json_encode($data);
curl_setopt($ch, CURLOPT_POST, true);
//Send blindly the json-encoded string.
//The server, IMO, expects the body of the HTTP request to be in JSON
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER,
array
(
'Content-Type:application/json',
'Content-Length: ' . strlen($data_string)
)
);
$result = curl_exec($ch);
curl_close($ch);
print_r($result);
echo '<pre>';
echo $_POST;
$jsonStr = file_get_contents('php://input'); //read the HTTP body.
var_dump($jsonStr);
var_dump(json_decode($jsonStr));
echo '</pre>';
The output of the above is the following:
"Your TEST POST is correct, please set the isTest (Boolean) attribute on the application to FALSE to actually apply."
Arraystring(0) ""
NULL
OK, the above confirms that I formatted the JSON data correctly by using json_encode, and the SOME FORCE.COM WEBSITE acknowledges that the value of 'isTest' is FALSE. However, I am not getting anything from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". I decided to just ignore that fact and set 'isTest' to FALSE, assuming that I am not getting any JSON data because I set 'isTest' to TRUE, but chaos ensues when I set 'isTest' to FALSE:
[{"message":"System.EmailException: SendEmail failed. First exception on row 0; first error: REQUIRED_FIELD_MISSING, Missing body, need at least one of html or plainText: []\n\nClass.careers_RestWebService.sendReceiptEmail: line 165, column 1\nClass.careers_RestWebService.postApplication: line 205, column 1","errorCode":"APEX_ERROR"}]
Arraystring(0) ""
NULL
I still do not get any JSON data, and ultimately, the email was unable to be sent. I believe that the issue is resulting from an empty email body because there is nothing coming from "var_dump($jsonStr)" or "var_dump(json_decode($jsonStr))". Can you help me retrieve the JSON POST? I would really appreciate any hints, suggestions, etc. Thanks.
I solved this question on my own. I was not sure if I was doing this correctly or not, but it turns out that my code was perfect. I kept refreshing my website, from where I am POSTing to SOME FORCE.COM WEBSITE. I believe that the people managing SOME FORCE.COM WEBSITE were having issues on their end. Nothing was wrong with what I did. For some reason, I got a code 202 and some gibberish text to go along with it. I would be glad to show the output, but I do not want to POST again for the sake of the people managing SOME FORCE.COM WEBSITE that I am POSTing to. Thank you guys for your help.
This question already has answers here:
curl POST format for CURLOPT_POSTFIELDS
(10 answers)
Closed 4 years ago.
I have this curl request below, which was successfully troubleshooted in another post. Right now, my PHP seems to work through this code without any errors, moves onto the next part of the IF statement and sends the confirmation email. It just doesn't update the database as it should from the web service. I will have to email the creator of the web service if this does not work but I just want to be sure that the code is fairly solid before I do this. Any one have any ideas? Here is the code:
$url = 'http://127.0.0.1:85/AccountCreator.ashx';
$curl_post_data = array(
'companyName' =>urlencode($companyName),
'mainContact' =>urlencode($mainContact),
'telephone1' =>urlencode($telephone1),
'email' => urlencode($email),
'contact2' => urlencode($contact2),
'telephone2' => urlencode($telephone2),
'email2' => urlencode($email2),
'package' => urlencode($package)
);
foreach($curl_post_data as $key=>$value) {$fields_string .=$key. '=' .$value.'&';
}
rtrim($fields_string, '&');
//die("Test: ".$fields_string);
$ch = curl_init();
curl_setopt ($ch, CURLOPT, $url);
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
curl_setopt ($ch, CURLOPT_POSTFIELDS, $fields_string);
$result = curl_exec($ch);
curl_close($ch);
Firstly, what is the problem? It would be easier to troubleshoot it if you explained exactly what the failure in the code was. Secondly, there are a couple of odd things you are doing in this code:
I don't see why you are doing
curl_setopt ($ch, CURLOPT_POST, count($curl_post_data));
CURLOPT_POST requires a boolean (true/false) setting. You should set it to true.
Secondly, you don't need to encode CURLOPT_POSTFIELDS manually. Make an array and let cURL deal with it internally:
$curl_post_data = array(
'companyName' =>$companyName,
'mainContact' =>$mainContact,
'telephone1' =>$telephone),
'email' => $email,
'contact2' => $contact2,
'telephone2' => $telephone2,
'email2' => $email2,
'package' => $package
);
These might not fix the problem, but they may help.
The CURLOPT_POSTFIELDS option accepts an associative array of POST-data. Probably better to use that one rather than to construct the query string yourself so you got someone else to blame when it blows up.
PHP Manual:
The full data to post in a HTTP "POST"
operation. To post a file, prepend a
filename with # and use the full path.
This can either be passed as a
urlencoded string like
'para1=val1¶2=val2&...' or as an
array with the field name as key and
field data as value. If value is an
array, the Content-Type header will be
set to multipart/form-data.