I am trying to run a php script in terminal to get a organized reply of cryptocurrency data. the full JSON array can be viewed at https://poloniex.com/public?command=returnTicker. The nested array isnt stacked with [] and parsing this format is becoming troublesome.
here is the code i used:
$fgc = json_decode(file_get_contents("https://poloniex.com/public?command=returnTicker"), true);
echo "Last Price: $".$fgc["last"]." Ask: ".$fgc["lowestAsk"]." Bid: ".$fgc["highestBid"];
echo PHP_EOL;
This is the error it gives me:
PHP Notice: Undefined index:
I have a feeling i need to define each coin however im not sure how to parse it.
other code i have tried:
$fgc = json_decode(file_get_contents("https://poloniex.com/public?command=returnTicker"), true);
$data = $fgc["BTC_BCN"];
foreach($data as $details){
echo "".$details["last"]." ".$details["lowestAsk"];
echo " ".$details["highestBid"];
echo PHP_EOL;
}
The error for this code is:
PHP Warning: Illegal string offset
Please help me understand how to parse this format. Thank you.
Related
I'm a beginner in json please help
I'm trying to access value of certain objects from an online published json file via php script and not able to do so following the examples from this forum
<?php
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primary topic"]["CompanyName"];
print $companyname;
?>
i get the following error
( ! ) Notice: Undefined index: primary topic in C:\wamp\www\json.php on line 4
Call Stack
# Time Memory Function Location
1 0.0000 244456 {main}( ) ..\json.php:0
I have tried single and double quotes, [0] for array but to no avail
You should have to use primaryTopic :
$str = file_get_contents('http://data.companieshouse.gov.uk/doc/company/02050399.json');
$json = json_decode($str, true);
$companyname = $json["primaryTopic"]["CompanyName"];
print $companyname;
Output will : ZENITH PRINT (UK) LIMITED
I think you had a mistake at 'primary topic' key. The key-name i saw in the response is 'primaryTopic'. Could you please check again?
Below is the code that I am currently using in which I pass an address to the function and the Nominatim API should return a JSON from which I could retrieve the latitude and longitude of the address from.
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = 'http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1';
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
// get the important data
$lati = $resp['lat'];
$longi = $resp['lon'];
// put the data in the array
$data_arr = array();
array_push(
$data_arr,
$lati,
$longi
);
return $data_arr;
}
The problem with it is that I always end up with an Internal Server Error. I have checked the Logs and this constantly gets repeated:
[[DATE] America/New_York] PHP Notice: Undefined index: title in [...php] on line [...]
[[DATE] America/New_York] PHP Notice: Undefined variable: area in [...php] on line [...]
What could be the issue here? Is it because of the _ in New_York? I have tried using str_replace to swap that with a + but that doesn't seem to work and the same error is still returned.
Also, the URL works fine since I have tested it out through JavaScript and manually (though {$address} was replaced with an actual address).
Would really appreciate any help with this, thank you!
Edit
This has now been fixed. The problem seems to be with Nominatim not being able to pickup certain values and so returns an error as a result
The errors you have mentioned don't appear to relate to the code you posted given the variables title and area are not present. I can provide some help for the geocode function you posted.
The main issue is that there are single quotes around the $url string - this means that $address is not injected into the string and the requests is for the lat/long of "$address". Using double quotes resolves this issue:
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
Secondly, the response contains an array of arrays (if were not for the limit parameter more than one result might be expected). So when fetch the details out of the response, look in $resp[0] rather than just $resp.
// get the important data
$lati = $resp[0]['lat'];
$longi = $resp[0]['lon'];
In full, with some abbreviation of the array building at the end for simplicity:
function geocode($address){
// url encode the address
$address = urlencode($address);
$url = "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&q={$address}&format=json&limit=1";
// get the json response
$resp_json = file_get_contents($url);
// decode the json
$resp = json_decode($resp_json, true);
return array($resp[0]['lat'], $resp[0]['lon']);
}
Once you are happy it works, I'd recommend adding in some error handling for both the http request and decoding/returning of the response.
I have this JSON (is from Steam Market):
{"success":true,"lowest_price":"$5.79","volume":"2,932","median_price":"$5.79"}
And I have this code:
$urlm = 'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name='.$name;
$market = json_decode(file_get_contents($urlm), true);
echo $market['lowest_price'];
But when I try it, they give me an error:
Notice: Undefined index: lowest_price
What is wrong? Because I have an other JSON with the same method and works perfect.
You should urlencode your varaiable:
$urlm = 'http://steamcommunity.com/market/priceoverview/?currency=1&appid=730&market_hash_name='. urlencode($name);
I'm trying to use PHP for a command-line script. I pass in a json string to it, and I'm trying to read the values out but getting an error when I do echo $user_inputs["foo"];, why is this? Am I forgetting something about json_decode, or is it about using STDIN?
my_test.php
// Get the STDIN.
$stdin = fopen('php://stdin', 'r');
// Initialize user_inputs_json which will be the entire stdin.
$user_inputs_json = "";
// Read all of stdin.
while($line = fgets($stdin)) {
$user_inputs_json .= $line;
}
// Create the decoded json object.
$user_inputs = json_decode($user_inputs_json);
// Try to echo a value. This is where I get my error (written out below).
echo $user_inputs["foo"];
fclose($stdin);
Run this in command line to pass JSON into it:
$ echo '{"foo":"hello world!", "bar": "goodnight moon!"}' | php my_test.php
I get this error:
Fatal error: Cannot use object of type stdClass as array in /Users/don/Desktop/my_test.php on line 20
By default json_decode converts JSON string into PHP object. If you want to get PHP array, use the second parameter of json_decode:
$user_inputs_array = json_decode($user_inputs_json, true);
If you need to always handle the passed in JSON as an array, set the second json_decode parameter to true to force it to decode as an array:
$user_inputs = json_decode($user_inputs_json, 1);
So I have been working on a school project and have gotten this code for a website to work sometimes but other times it returns the error:
Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 27
Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 27
Ask
Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 39
Notice: Trying to get property of non-object in C:\xampp\htdocs\schoolproj\getdata.php on line 39
for the php code:
<html>
<body>
<?php echo $_POST['name']; ?>!<br>
<?php
$endpoint = "http://query.yahooapis.com/v1/public/yql";
$ticker = "'".$_POST["ticker"]."'";
$query = urlencode("env 'store://datatables.org/alltableswithkeys';select * from yahoo.finance.quotes where symbol in (".$ticker.")");
$ch = curl_init($endpoint.'?q='.$query. '&format=json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
if (curl_error($ch)){
die(curl_error($ch));
}
curl_close($ch);
//echo'<pre>';
$result = json_decode($result);
$symbol = $result->query->results->quote->symbol;
print_r($symbol);
?>
Ask
<?php
$Ask = $result->query->results->quote->Ask;
print_r($Ask);
?>
</body>
</html>
I was wondering if anyone had some advice as to how I could permanently fix the problem or have some sort of error handling. I am new to this so any help would be great. Thanks!
The problematic lines if the code you gave is the whole getdata.php file are:
l.27: $symbol = $result->query->results->quote->symbol;
l.39: $Ask = $result->query->results->quote->Ask;
And the error is telling you that at one point in this your are accessing a property of something that is not an object.
Considering you are saying it sometimes work and sometimes doesn't, it's likely that there are occasional errors, either in your query (depending on your input) or with datatables.org (see this old question on developer.yahoo which indicates that queries would fail when datatables.org doesn't respond).
Then if there is an error, the json you receive will have a structure like below (this is an error I got initially when trying your code because I had forgottent to enclose the ticker in quotes).
{
"error": {
"lang":"en-US",
"description":"Query syntax error(s) [line 1:95 mismatched input 'in' expecting ISNOTNULL]"
}
}
In this result you don't have the query attribute and thus is fails when you try to access it. You should then first check if there is an error (looking for the error attribute), and only if there is none try and access the query results.
To check for the error, you could use something like
if (property_exists($result, "error")) {
// your error handling
} else {
// your current code accessing the results
}