How can I get variables "price_usd" for bitcoin & ethereum from JSON url https://api.coinmarketcap.com/v1/ticker
This works:
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
$lastPrice = $json[0]["price_usd"];
echo $lastPrice;
However, I would like to do something like this:
<?php
$url = "https://api.coinmarketcap.com/v1/ticker/";
$fgc = file_get_contents($url);
$json = json_decode($fgc, TRUE);
function price($ticker) {
foreach($json[] as $item) {
if($item->id == $ticker) {
echo $item->price_usd;
}
}
}?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php echo price("bitcoin");?>
<?php echo price("etheruem");?>
</body>
</html>
You can use array_column for this:
$json = json_decode($fgc, TRUE);
// following line will create assoc array as key => value for 'price_usd' as key and 'id' as value
$js = array_column($json, 'price_usd', 'id');
echo $js["bitcoin"];
General Function:
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
function price($curr) {
global $decoded_json;
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
echo price("bitcoin");
echo price("ethereum");
Another solution without global var:
// this will create a new request to api.coinmarketcap.com on each call
function price($curr) {
$decoded_json = json_decode(file_get_contents("https://api.coinmarketcap.com/v1/ticker/"), TRUE);
$js = array_column($decoded_json, 'price_usd', 'id');
return $js[$curr];
}
Now that the question is updated, you can just cast the $js to object and use it like an object:
$js = (object) $js;
echo $js->bitcoin;
Related
I am not able to display data from this url using php json decode:
https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it
here is the data provider:
https://mymemory.translated.net/doc/spec.php
thanks.
What I want is to setup a form to submit words and get translation back from their API.
here is my code sample:
<?php
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
// parse the JSON
$data = json_decode($json);
// show the translation
echo $data;
?>
My guess is that you might likely want to write some for loops with if statements to display your data as you wish:
Test
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
if (isset($data["responseData"])) {
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html = $value;
} else {
continue;
}
}
} else {
echo "Something is not right!";
}
echo $html;
Output
Ciao Mondo!
<?php
$html = '
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
';
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Hello%20World!&langpair=en|it');
$data = json_decode($json, true);
foreach ($data["responseData"] as $key => $value) {
// This if is to only display the translatedText value //
if ($key == 'translatedText' && !is_null($value)) {
$html .= '<p>' . $value . '</p>';
} else {
continue;
}
}
$html .= '
</body>
</html>';
echo $html;
?>
Output
<!DOCTYPE html>
<html lang="en">
<head>
<title>read JSON from URL</title>
</head>
<body>
<p>Ciao Mondo!</p>
</body>
After many researches I got it working this way:
$json = file_get_contents('https://api.mymemory.translated.net/get?q=Map&langpair=en|it');
$obj = json_decode($json);
echo $obj->responseData->translatedText;
thank you all.
I've a JSON response from some web service
{
"success":true,
"timestamp":1503291248,
"quotes":{
"SAD":"ABC",
"LOVE":"XYZ",
"FRIENDSHIP":"SOME",
"ENMITY":"LOREM IPSUM",
... //indicates there are a lot more categories
}
}
I have tried to echo data using this script
<?php
$url = 'MY_URL';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $idx=>$json ) {
echo $idx;
}
?>
this prints
successtermsprivacytimestampsourcequotes
but getting empty response, how can I echo/save above josn data in mySql?
<?php
$url = '{
"success":true,
"timestamp":1503291248,
"quotes":{
"SAD":"ABC",
"LOVE":"XYZ",
"FRIENDSHIP":"SOME",
"ENMITY":"LOREM IPSUM",
... //indicates there are a lot more categories
}
}';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $idx=>$json ) {
if(is_array($json))
{
foreach($json as $iidx=>$jjson)
{
echo $iidx.":".$jjson;
}
}
else
{
echo $idx.":".$json;
}
}
$ins_qry = 'INSERT INTO json_table(jsonvalues) values ("'.$json.'")';
$exec_qry = mysqli_query($link,$ins_qry);
?>
This will print json data.
To save this json data in mysql, you can directly insert the $json value into text column of a MySQL table.
$json = file_get_contents('url_here');
$obj = json_decode($json);
echo $obj->access_token;
Try this..
$url = 'MY_URL';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach ( $json as $val) {
echo $val['success']; //same for other keys
}
How can I get variables "price_usd" and "price_btc" from JSON url https://api.coinmarketcap.com/v1/ticker/ethereum/? I wrote a script but nothing happens.
<?php
$tick = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/');
$url = $tick;
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$usd = $data[0]["price_usd"];
echo $usd;
?>
Your code use a file_get_contents twice, look at would be:
<?php
$tick = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/');
$url = $tick;
echo $url;
//$json = file_get_contents($url);
$data = json_decode($tick, TRUE);
$usd = $data[0]["price_usd"];
echo $usd;
?>
Try this
<?php
$json = file_get_contents('https://api.coinmarketcap.com/v1/ticker/ethereum/');
$data = json_decode($json);
var_dump($data[0]->price_usd);
?>
I need help with fetching only attraction data,
i have this php script on my website:
<?php $json_string = 'http://framecreators.nl/efteling/data.php'; $jsondata file_get_content($json_string); $json_o=json_decode(utf8_encode($data)); $attractie = $json_o['Id']['Type']; echo $attractie ?>
and this json data:
http://framecreators.nl/efteling/data.php
I need to convert only a Id and type, ff somebody can help me.
To access the data you're looking for, you'll need to do something like this:
foreach ($json_o['AttractionInfo'] as $a) {
echo $a['Id']; //or whatever you're planning to do with this data
ech0 $a['Type'];
}
<?php
$json_data = file_get_contents('http://framecreators.nl/efteling/data.php');
$data = json_decode($json_data);
$array = [];
foreach($data->AttractionInfo as $item) {
$array['id'][] = $item->Id;
$array['type'][] = $item->Type;
}
echo "<pre>";
print_r($array);
echo "</pre>";
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
foreach($array as $r)
{
echo "ID->".$r['Id'];
echo '';
echo "Type->".$r['Type'];
echo '';
}
$url = "http://framecreators.nl/efteling/data.php";
$content = file_get_contents($url);
$data = json_decode($content,TRUE);
$array = $data['AttractionInfo'];
if(is_array($array))
{
foreach($array as $r)
{
echo $r['Id'];
echo $r['Type'];
}
}
I'm trying to print my key/value pairs of data in my CodeIgniter view. However, I'm getting the following error. What I'm I doing wrong?
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: data
Filename: views/search_page2.php
Line Number: 8
application/controller/search.php
// ...
$this->load->library('/twitter/TwitterAPIExchange', $settings);
$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?username=johndoe';
$requestMethod = 'GET';
$twitter = new TwitterAPIExchange($settings);
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
// ...
application/views/search_page2.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Twitter Test</title>
</head>
<body>
<?php print_r($data); ?>
<?php foreach ($data as $key => $value): ?>
<h2><?php echo $key . ' ' . $value . '<br />'; ?></h2>
<?php endforeach ?>
</body>
</html>
to get the data array accessible in the view do like
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$data['data'] = $data;
$this->load->view('search_page2', $data);
else only the variables with names as its keys will be available in the view not the data variable we pass.
update:
this is in response to your comment to juan's answer
Actually if you are trying make it working in the other way proposed.
controller code will be having no change from the code you posted.
$data['url'] = $url;
$data['getfield'] = $getfield;
$data['requestMethod'] = $requestMethod;
$this->load->view('search_page2', $data);
but in the view code you will need to just do.
<h2>url <?PHP echo $url; ?><br /></h2>
<h2>getfield <?PHP echo $getfield; ?><br /></h2>
<h2>requestMethod <?PHP echo $requestMethod; ?><br /></h2>
instead of the foreach loop as your keys in $data are already available as respective named variables inside the view.
The variables to use in your template are
$url, $getfield, $requestMethod
$data is the container for the variables that are passed to the view and not accessible directly
If you do need $data accessible to the view, use a different wrapper object
$container = array();
$container ['url'] = $url;
$container ['getfield'] = $getfield;
$container ['requestMethod'] = $requestMethod;
$container ['data'] = $data;
$this->load->view('search_page2', $container);