I am trying to extract the individual data strings from a curl and json_decode result, but cannot manage to target the array elements correctly:
API:
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
Result:
{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}
PHP:
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
Also tried:
echo 'Bid: '.$obj['Bid'].'<br/>';
echo 'Ask: '.$obj['Ask'].'<br/>';
echo 'Last: '.$obj['Last'].'<br/>';
You need to add a true parameter to your json_decode
Like
json_decode($execResult, true);
Else you get a stdObject with the decoded data.
Then you should be able to use $obj['result']['Bid'] aso.
The use of json_decode has an optional second parameter - boolean - that either returns the data as an object or as an array.
{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}
$obj = json_decode( $execResult ); /* will return an object */
echo $obj->result->Bid;
$obj = json_decode( $execResult, true ); /* will return an array */
echo $obj['result']['Bid'];
Just ran this as the test..
$data='{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}';
$obj = json_decode( $data ); /* will return an object */
echo $obj->result->Bid;
$obj = json_decode( $data, true ); /* will return an array */
echo $obj['result']['Bid'];
which displayed:
0.043500030.04350003
Use this way:
echo 'Bid: '.$obj->result->Bid.'<br/>';
echo 'Ask: '.$obj->result->Ask.'<br/>';
echo 'Last: '.$obj->result->Last.'<br/>';
let
$json = '{"success":true,"message":"","result":{"Bid":0.04350003,"Ask":0.04395399,"Last":0.04350003}}';
$obj = json_decode($json, true);// decode and convert it in array
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
Try using json_decode($string, true); as an array
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult, true);
echo 'Bid: '.$obj['result']['Bid'].'<br/>';
echo 'Ask: '.$obj['result']['Ask'].'<br/>';
echo 'Last: '.$obj['result']['Last'].'<br/>';
OR using json_decode($string); as an object
$ch = curl_init($uri);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('apisign:'.$sign));
$execResult = curl_exec($ch);
$obj = json_decode($execResult);
echo 'Bid: '.$obj->result->Bid.'<br/>';
echo 'Ask: '.$obj->result->Ask.'<br/>';
echo 'Last: '.$obj->result->Last.'<br/>';
Related
I have the json response like this from fetching via URL, using json_decode.
function get_data($url)
{
$ch = curl_init();
$timeout = 3;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$domain = "http://localhost:3000/";
$getcontent = get_data($domain);
$data = json_decode($getcontent, true);
After fetched, the response is:
{"Data":{"Players":"2,621","Kills":"87","Medals":"908","Cards":"324","TimePlayed":"88hours","GamesWon":"328","ObjectiveTime":"05:25:02"}}
I would like to remove Data object to be just the response body in PHP.
I have tried: $data[0]['Players']; but it is not looking through the json data body.
$players = $data[0]['Players'];
So I display it as:
echo 'Players: ' . $players . ';
Note: Sometimes that Data will always changed dynamic like Responses, Players, PlayerName, Date.
Can I use $data['. $playername . ']["Player"]; ?
If you don't know the key you can use key() function of PHP. Whatever the value of your first key you can access it like this.
Try this code demo
<?php
ini_set('display_errors', 1);
$string='{"Data":{"Players":"2,621","Kills":"87","Medals":"908","Cards":"324","TimePlayed":"88hours","GamesWon":"328","ObjectiveTime":"05:25:02"}}';
$array=json_decode($string,true);
print_r($array[key($array)]["Players"]);
Solution 2: Try this code snippet here
<?php
ini_set('display_errors', 1);
$string='{"Data":{"Players":"2,621","Kills":"87","Medals":"908","Cards":"324","TimePlayed":"88hours","GamesWon":"328","ObjectiveTime":"05:25:02"}}';
$array=json_decode($string,true);
extract($array[key($array)]);
echo $Players;
echo $Kills;
echo $Medals;
echo $Cards;
echo $TimePlayed;
echo $GamesWon;
echo $ObjectiveTime;
Whole code:
<?php
ini_set('display_errors', 1);
function get_data($url)
{
$ch = curl_init();
$timeout = 3;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$domain = "http://localhost:3000/";
$getcontent = get_data($url);
$data = json_decode($getcontent, true);
print_r($data[key($data)]["Players"]);
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);
?>
Please help me get JSON result - "col1":"64.7020" to $result.
{"query":{"count":1,"created":"2016-08-28T09:50:07Z","lang":"ru-RU","diagnostics":{"publiclyCallable":"true","url":{"execution-start-time":"1","execution-stop-time":"2","execution-time":"1","content":"http://finance.yahoo.com/d/quotes.csv?e=.csv&f=c4l1&s=USDRUB=X"},"user-time":"2","service-time":"1","build-version":"0.2.48"},"results":{"row":{"col0":"RUB","col1":"64.7020"}}}}
$tick=file_get_contents('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dc4l1%26s%3DUSDRUB%3DX%22%3B&format=json&diagnostics=true&callback=');
$url = $tick;
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$result ??
echo col1 ???????
You have called file_get_contents twice. $tick will have the json returned by yahoo
$tick = file_get_contents('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20csv%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fd%2Fquotes.csv%3Fe%3D.csv%26f%3Dc4l1%26s%3DUSDRUB%3DX%22%3B&format=json&diagnostics=true&callback=');
$json_a = json_decode($tick, TRUE);
echo $json_a["query"]["results"]["row"]["col1"];
I would like to do parse XML for the url:
http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0
I am the beginner of PHP and tried the code as below:
$url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
$xml = simplexml_load_file($url) or die("feed not loading");
print_r($xml);
var_dump($xml);
I would like to do echo for each attribute e.g. lat, lon, range.. for this XML url.
I found many resource in stackoverflow which the XML is quite standard. I cannot find an example which is used for this format of XML:
Anyone could give me an idea? Thanks.
$url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
$status = curl_getinfo($ch,CURLINFO_HTTP_CODE);
curl_close($ch);
if($status==200){
$x = new SimpleXMLElement($data,LIBXML_NOCDATA);
echo 'lat: '.$x->cell['lat'];
echo 'lon: '.$x->cell['lon'];
echo 'range: '.$x->cell['range'];
}
Update:
This is an alternative to curl. If you have curl installed, use curl, it is faster.
$url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
$data = file_get_contents($url);
$x = new SimpleXMLElement($data,LIBXML_NOCDATA);
$lat = $x->cell['lat'];
$lng = $x->cell['lon'];
$range = $x->cell['range'];
echo 'lat: '.$lat.'<br>';
echo 'lng: '.$lng.'<br>';
echo 'range: '.$range.'<br>';
Please try this
$content = file_get_contents('http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0');
$x = new SimpleXmlElement($content);
foreach($x->cell as $entry) {
echo $entry['lat']."==".$entry['lon']; exit;
}
$url = "http://www.opencellid.org/cell/get?key=myapikey&mcc=250&mnc=99&cellid=29513&lac=0";
$xml = simplexml_load_file($url) or die("feed not loading");
$attr = array("lat", "lon"); //list attr you require
foreach($xml->cell as $cell){
$data = $cell->attributes();
foreach ($attr as $key) {
// echo "<br>key: $key, value: " . $data[$key];
//edit to insert
$columns[] = $key;
$values[] = $data[$key];
}
echo $query = "insert into table_name(".implode(',',$columns).") values (".implode(',',$values).")";
}
I am trying to use http://api.twitter.com/1/trends/current.json?exclude=hashtags however I am having some trouble.
So, I'm trying to use:
<?php
$init = 'http://api.twitter.com/1/trends/current.json?exclude=hashtags';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$init);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$result = curl_exec($ch);
curl_close($ch);
$obj = json_decode($result, true);
foreach ($obj[0]['trends'] as $trend) {
print $trend['query'];
echo "<br>";
print $trend['name'];
echo "<hr>";
}
?>
And I am getting this Error:
Notice: Undefined offset: 0 in \index.php on line 11
Warning: Invalid argument supplied for foreach() \index.php on line 11
You read the JSON wrong. You need to do something like the following:
foreach ($obj['trends']['2011-02-23 18:00:00'] as $trend) {
print $trend['query'];
echo "<br>";
print $trend['name'];
echo "<hr>";
}
If I am not wrong
$obj = json_decode($result, true);
would produce an array and not an object. secondly using the twitter api is as simple as:
<?php
function get_trends($woeid){
return json_decode(file_get_contents("http://api.twitter.com/1/trends/".$woeid.".json?exclude=hashtags", true), false);
}
$data = get_trends(23424848); //23424848 is woeid for India...
$trends = $data[0]->trends;
echo "<ul>";
if(!empty($trends)){
foreach($trends as $trend){
echo '<li>'.$trend->name.'</li>';
}
}
echo "</ul>";
?>