I'm trying to create a php script to display only the "credit" value of the account 491027679-102 but it does not work, I get a white screen. Can you help me solve this problem?
This is the script I did, where I drew?
<?php
$url = 'https://www.vohippo.com/it/vohippo/user/ApiWhsGetSubList?email=mail#example.com&apikey=123';
$content = file_get_contents($url);
$apiResult = json_decode($content);
($apiResult['status'] !== 'ok') &&
trigger_error('Unexpected API Result');
empty(($account = array_filter($apiResult['result'], function($item) {
return $item['account'] === '491027679-102';
}))) && trigger_error('Account not found.');
echo $account[0]['credit'];
?>
If you already know the index of the parent array for the credit, you can do it as above echo $account[0]['credit'];.
If you don't know the index of the parent and it changes everytime in the $account variable, you should loop through the array.
Instead of using echo $account[0]['credit'];, you should loop through the array:
foreach ($account as $key => $value) {
echo $account[$key]['credit'];
}
Your script:
<?php
// https://stackoverflow.com/questions/54390848/view-json-api-value-on-php-file
$url = 'https://www.vohippo.com/it/vohippo/user/ApiWhsGetSubList?email=webmasterlertux#gmail.com&apikey=4c62479846b0aea59ac007f3a283b581';
$content = file_get_contents($url);
$apiResult = json_decode($content);
($apiResult['status'] !== 'ok') && trigger_error('Unexpected API Result');
empty(($account = array_filter($apiResult['result'], function($item) {
return $item['account'] === '491027679-102';
}))) && trigger_error('Account not found.');
echo $account[0]['credit'];
?>
My php version:
php-fpm at 87a5be43419e in /var/www/html
$ php --version
PHP 7.2.4 (cli) (built: Apr 5 2018 00:37:24) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.2.0, Copyright (c) 1998-2018 Zend Technologies
Running your script:
$ php question-54390848.php
Fatal error: Uncaught Error: Cannot use object of type stdClass as array in /var/www/html/question-54390848.php:9
Stack trace:
#0 {main}
thrown in /var/www/html/question-54390848.php on line 9
The error is in line 9 because you try to access an array when you an object, because in line 7 json_decode($content) gives you an object, but to get an array you need to do `json_decode($content, true).
Lets' fix it:
<?php
// https://stackoverflow.com/questions/54390848/view-json-api-value-on-php-file
$url = 'https://www.vohippo.com/it/vohippo/user/ApiWhsGetSubList?email=webmasterlertux#gmail.com&apikey=4c62479846b0aea59ac007f3a283b581';
$content = file_get_contents($url);
// Adding `true` to enable decoding to an array
$apiResult = json_decode($content, true);
($apiResult['status'] !== 'ok') && trigger_error('Unexpected API Result');
$account = [];
empty(($account = array_filter($apiResult['result'], function($item) {
return $item['account'] === '491027679-102';
}))) && trigger_error('Account not found.');
// using array_filter will return the array entries as they have been matched,
// thus your match happens in the array entry with key `1`, but you try to
// access the entry `0` in the echo statement.
// so using array_values will return all values in the array indexed from key `0`.
$account = array_values($account);
echo $account[0]['credit'];
?>
Another fix was needed in order you can access the $account[0] in your echo statement. Please read the comments in the code.
Running your script again:
php-fpm at 87a5be43419e in /var/www/html
$ php question-54390848.php
0.0000
NOTE: Your script needs to have more checks for errors with the response and when accessing the $account array.
SECURITY ALERT
You have published the API KEY in your question:
$url = 'https://www.vohippo.com/it/vohippo/user/ApiWhsGetSubList?email=webmasterlertux#gmail.com&apikey=4c62479846b0aea59ac007f3a283b581';
Now everyone can access this service in your behalf and if is a paid one you will be the one paying the bill.
Please reset this API KEY immediately and get a new one
API KEYS best practice is to be sent in the header
Related
I have the following url:
https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1
I want to access the final_balance from the output of the url.
I have the following code:
$value = file_get_contents($url);
$FinalBalance = $value["final_balance"];
var_dump($FinalBalance);
Error PHP Warning: Illegal string offset 'final_balance'
I also tried the following code:
$value = file_get_contents($url);
$json = json_decode($value);
var_dump($json);
$FinalBalance = $json["final_balance"];
var_dump($Final_Balance);
Error PHP Fatal error: Uncaught Error: Cannot use object of type stdClass as array
Your are near to finish that stuff but I will write down desired solution. Please have a look.
$url="https://blockchain.info/multiaddr?active=1AT4ES3ee1N6iBzzbdK8xvcAV3CBTRKcbS|1FHcYth4LRJMwNx2y8NR5DH7sYCiVzXs3Y&n=1";
$value = file_get_contents($url);
$FinalBalance = $value;
$data=json_decode($FinalBalance);
echo $data->wallet->final_balance;
echo $data->addresses[0]->final_balance;
echo $data->addresses[1]->final_balance;
exit;
You are going to access the inner object so you have to provide proper reference whether it is an array or an object.
i have following problem:
in a function, i put in an array with at least 700 names. I get out an array with all information about their releases from the last 10 days.
The function gets via iTunes API a json response, which i want to use for further analyzings.
Problem:
- while executing function, it takes about 3mins to finish it.
- homepage is not reachable for others, while i execute it:
(Error on Server: (70007)The timeout specified has expired: AH01075: Error dispatching request to : (polling)) --> Running out of memory?
Questions:
- how to code this function more efficient?
- how to code this function without using to much memory, shall i use unset(...) ??
Code:
function getreleases($artists){
# print_r($artists);
$releases = array();
foreach( $artists as $artist){
$artist = str_replace(" ","%20",$artist);
$ituneslink = "https://itunes.apple.com/search?term=".$artist."&media=music&entity=album&limit=2&country=DE";
$itunesstring = file_get_contents($ituneslink);
$itunesstring = json_decode($itunesstring);
/*Results being decoded from json to an array*/
if( ($itunesstring -> resultCount)>0 ){
foreach ( $itunesstring -> results as $value){
if( (date_diff(date_create('now'), date_create( ($value -> releaseDate )))->format('%a')) < 10) {
#echo '<br>Gefunden: ' . $artist;
$releases[] = $value;
}
}
}else{
echo '<br><span style="color:red">Nicht gefunden bei iTunes: ' . $artist .'</span>';
}
unset($ituneslink);
unset($itunesstring);
unset($itunesstring2);
}
return $releases;
}
The problem lies in the fact that every time that function is executed, your server needs to make 700+ API Calls, parse the data, and work your logic on it.
One potential solution is to use Wordpress's transients to 'cache' the value (or perhaps even the whole output), this way, it won't have to execute that strenuous function on every connection, it'll just pull the data from the transient. You can set an expiry date for a transient, so you can have it refetch the information every X days/hours.
Take a look at this article from CSS Tricks that walks you through a simple example using transients.
But the problem is not fixed. While updating the stuff and getting 700 items from iTunes API and while Running in the for-loop, the homepage is getting out of memory. although homepage is not reachable from my computer. I just tried for a "timeout" or "sleep" sothat the script is searching for stuff every few seconds. But it doesn't change it.
I just improved: Changed "foreach" to "for" because of memory reasons. Now variables are not being copied. Are there more problems :-/ ??
I've got to for-loops in there. Maybe $itunesstring is being copied ?
if(!function_exists('get_contents')){
function get_contents(&$url){
// if cURL is available, use it...
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$cache = curl_exec($ch);
curl_close($ch);
return $cache;
}
}
function getfromituneslink(&$link,&$name){
$name = str_replace("'","",$name);
$name = substr($name, 0, 14);
$result = get_transient("getlink_itunes_{$name}");
if(false === $result){
$result = get_contents($link);
set_transient("getlink_itunes_{$name}",$result, 12*HOUR_IN_SECONDS);
}
return $result;
}
function getreleases(&$artists){
$releases= array();
while( 0 < count($artists)){
$itunesstring = array();
$artist = array_shift($artists);
$artist = str_replace(" ","%20",$artist);
$ituneslink = "https://itunes.apple.com/search?term=".$artist."&media=music&entity=album&limit=2&country=DE";
$itunesstring = getfromituneslink($ituneslink,$artist);
unset($ituneslink);
$itunesstring = json_decode($itunesstring);
if( ($itunesstring -> resultCount)>0 ){
#for($i=0; $i< (count($itunesstring -> results))-1; ++$i)
while( 0 < count(($itunesstring -> results))){
$value = array_shift($itunesstring -> results);
#$value = &$itunesstring[results][$i];
#foreach ( $itunesstring -> results as $value)
if( (date_diff(date_create('now'), date_create( ($value -> releaseDate )))->format('%a')) < 6) {
$releases[] = array($value->artistName, $value->collectionName, $value->releaseDate, str_replace("?uo=4","",$value -> collectionViewUrl));
unset($value);
}
}
}else{
echo '<br><span style="color:red">Nicht gefunden bei iTunes: ' . str_replace("%20"," ",$artist) .'</span>';
}
unset($ituneslink);
unset($itunesstring);
}
return $releases;
}
I don't know, where the problem is. :-(
Any other possibilty to let the function run to get the information one by another
I'm trying to parse JSON sent by POST to my webservice.
I'm using Advanced Rest Client tool for Google Chrome to test restapi.
How can I read this request and response to it?
I'm sending key called "format" and "json" as value for this key. I'm adding JSON like
"{"id":"235325"}"
Part of my PHP API code:
if( strcasecmp($format,'json') == 0 )
{
//how to read that id = 235325?
}
Try the json_decode() function. It is the standard function to parse json in php.
If want to work with array:
$json = '{"id":"235325"}';
$array = json_decode($json, true);
foreach($array as $element){
if($element == 0){
}
}
With object:
$json = '{"id":"235325"}';
$object = json_decode($json);
if($object->id == 0){
}
I have a few console command in Symfony2 and I need to execute one command from another command with some parameters.
After successfull execution of the second command I need to get the result (as an array for example), not the display output.
How can I do that?
Here you can have a basic command inside a command. The output from the second command can be a json, then you just have to decode the output json to retrieve your array.
$command = $this->getApplication()->find('doctrine:fixtures:load');
$arguments = array(
//'--force' => true
''
);
$input = new ArrayInput($arguments);
$returnCode = $command->run($input, $output);
if($returnCode != 0) {
$text .= 'fixtures successfully loaded ...';
$output = json_decode(rtrim($output));
}
you have to pass the command in the arguments array, and to avoid the confirmation dialog in doctrine:fixtures:load you have to pass --append and not --force
$arguments = array(
'command' => 'doctrine:fixtures:load',
//'--append' => true
''
);
or it will fail with error message “Not enough arguments.”
There is an new Output class (as of v2.4.0) called BufferedOutput.
This is a very simple class that will return and clear the buffered output when the method fetch is called:
$output = new BufferedOutput();
$input = new ArrayInput($arguments);
$code = $command->run($input, $output);
if($code == 0) {
$outputText = $output->fetch();
echo $outputText;
}
I did the following
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Output\StreamOutput;
$tmpFile = tmpfile();
$output = new StreamOutput($tmpFile);
$input = new ArrayInput(array(
'parameter' => 'value',
));
$command = . . .
$command->run($input, $output);
fseek($tmpFile, 0);
$output = fread($tmpFile, 1024);
fclose($tmpFile);
echo $output;
¡it works!
I understand it's old post and above answers solves the problem with a bit of digging. In Symfony2.7, I had a bit issue making it work, so with above suggestions, I dug a little and have compiled the full answer here. Hope it will be useful for someone.
Using Console command under console command
As an update for Onema's answer, in Symfony 3.4.x (used by Drupal 8),
you also need to set setAutoExit(false),
and the command returns an int(0) if successful.
Here's the updated example that I'm using to script composer commands in php for a Drupal 8.8 project. This gets a list of all composer packages as json, then decodes that into a php object.
<?php
require __DIR__.'/vendor/autoload.php';
use Symfony\Component\Console\Output\BufferedOutput;
use Symfony\Component\Console\Input\ArrayInput;
use Composer\Console\Application;
$input = new ArrayInput([
'command' => 'show',
'--format'=>'json',
]);
$output = new BufferedOutput();
$application = new Application();
// required to use BufferedOutput()
$application->setAutoExit(false);
// composer package list, formatted as json, will be barfed into $output
$status = $application->run($input, $output);
if($status === 0) {
// grab the output from the $output buffer
$json = $output->fetch();
// decode the json string into an object
$list = json_decode($json);
// Profit!
print_r($list);
}
?>
The output will be something like this:
stdClass Object
(
[installed] => Array
(
... omitted ...
[91] => stdClass Object
(
[name] => drupal/core
[version] => 8.9.12
[description] => Drupal is an open source content management platform powering millions of websites and applications.
)
... omitted ...
)
)
With the help of Onema's hint Google found the rest of the solution for me here.
I am attempting to write PHP code to interact with JSON output from Mapquest's Open API / Open Street Map service. I have listed it below. I have been using this code in my Drupal 6 implementation. This code returns no output. When I use it, json_last_error() outputs 0.
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode(var_export($json));
$foo .= $obj->{'fuelUsed'};
$output .= foo;
return $output;
}
You can view the raw JSON output by following the URL. In this function I am expecting to get 1.257899 as my output. I have two questions:
(1) What can I call so I get items out of my array. For instance, how can I get the value represented in JSON "distance":26.923 out of the array?
(2) Is it possible am I running into a recursion limit issue that I've read about in the PHP Manual?
If you read the manual page for json_decode carefully, you'll notice there is a parameter (false by default) that you can pass to have it return an array rather than an object.
$obj = json_decode($json, true);
So:
<?php
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json, true);
//var_dump($obj);
echo $obj['route']['fuelUsed'];
}
json_test_page();
Remove the var_export function from json_decode.
You're trying to convert information about a string to json.
I was able to get the fuelUsed property this way
function json_test_page() {
$url = 'http://open.mapquestapi.com/directions/v1/route?outFormat=json&from=40.037661,-76.305977&to=39.962532,-76.728099';
$json = file_get_contents($url);
$obj = json_decode($json);
return $obj->route->fuelUsed;
}