I'm trying to pull the highlighted variable from this API:
{
"timestamp":{
"total":1486424886,
"exchanges":{
"NEG":1486423855,
"MBT":1486424738,
"LOC":1486422237,
"FOX":1486424483,
"FLW":1486411044,
"B2U":1486424811,
"ARN":1486405596
}
},
"ticker_24h":{
"total":{
"last":**3011.8756088755**, // <---
"high":4073.32,
"low":2631.58,
...
http://api.bitvalor.com/v1/ticker.json
This is my code so far:
<html>
<script src="http://code.jquery.com/jquery-1.12.0.min.js"></script>
<table width="auto">
<tr><td>BTC/BRL (Bitvalor)</tr></td>
<tr><td>
<?php
$url1 = "http://api.bitvalor.com/v1/order_book_stats.json";
$fgc1 = file_get_contents($url1);
$json1 = json_decode($fgc1, true);
$price1 = $json1["ticker_24h.total.last"];
echo $price1;
?>
</tr></td>
</table>
</html>
What am I missing?
You access decoded JSON like an associative array:
$price1 = $json1['ticker_24h']['total']['last'];
Make sure you use an isset in case the format of data changes or the response is not what you expect.
Related
I'm working on a PHP script and I want it to fetch this from steam api:
Steam api example
This is my code so far:
<!DOCTYPE html>
<html>
<head>
<title>
Test
</title>
</head>
<body style="text-align:center;">
<form method="post">
<input type="submit" value="OK" name="kk"/>
</form>
<?php
if(isset($_POST['kk'])) {
$json = file_get_contents('https://api.steampowered.com/ICSGOServers_730/GetGameServersStatus/v1/?key=STEAM API KEY HERE');
$obj = json_decode($json);
echo $obj->result;
}
?>
</head>
</html>
How can I fetch it?
You are trying to echo an stdClass as per your comments. That is why the error.
You can access the data (marked in red in the attached image ) like this
<?php
if(isset($_POST['kk'])) {
$json = file_get_contents('https://api.steampowered.com/ICSGOServers_730/GetGameServersStatus/v1/?key=STEAM API KEY HERE');
$obj = json_decode($json);
echo $obj->result->services->SessionsLogon;
echo $obj->result->services->SteamCommunity;
echo $obj->result->services->IEconItems;
}
If you are more comfortable with arrays instead of stdClass you can use $obj = json_decode($json, true) and access the elements with echo $obj['result']['services']['SessionsLogon'] etc.
To get a human readable output of the stdClass or the array you should use pre and print_r instead of just var_dump. For eg. echo '<pre>' . print_r($obj, true) . '</pre>';
I have an XML file I want to read, but can't seem to make sense of it.
To access the file I pulled you can type in:
http://www.zillow.com/webservice/GetDeepSearchResults.htm?zws-id=X1-ZWz1gyo1562s5n_6sext&address=155+Demar+Blvd&citystatezip=Canonsburg%2C+PA
I'm doing this through PHP, so my code looks like:
<html>
<head>
<title>Hellow World</title>
</head>
<body>
<?php
$zillow_id = 'X1-ZWz1gyo1562s5n_6sext';
$search = '155 Demar Blvd';
$citystate = 'Canonsburg PA';
$address = urlencode($search);
$citystatezip = urlencode($citystate);
$url = "http://www.zillow.com/webservice/GetSearchResults.htm?zws-id=$zillow_id&address=$address&citystatezip=$citystatezip";
$result = file_get_contents($url);
$data = simplexml_load_string($result);
echo $data->response->results->result->lotSizeSqFt . "<br>";
?>
</body>
</html>
I had expected this code to result in the printout of the lot size - in square feet - to the screen. No dice.
However, the line of code:
echo $data->response->results->result->zpid . "<br>";
returns the expected value for the zpid parameter: 49785503.
In an ideal world the line of code:
echo $data->response->results->result->lotSizeSqFt . "<br>";
would return: 9000.
What am I doing wrong?
You're using the wrong endpoint in your code.
Your endpoint:
http://www.zillow.com/webservice/GetSearchResults.htm
The correct endpoint:
http://www.zillow.com/webservice/GetDeepSearchResults.htm
Using the GetDeepSearchResults will return the results you're looking for.
I have a program that is failing because it's not finding the $post in the search of the array, so it's continuing to add each time. I have used the other suggested method of using a foreach loop, with strpos, such as:
if (strpos($data, $posts) !== false), and this will work find the $post, but it will also find the rest and run against everything in the data/array. hence why I would just like it to search the array, if it's not there add it, if it is, just say it's there or checking in... I've spent 3 days using in_array, array_search, etc, now I'm asking for help...
<html>
<body>
<?php
$post = $_POST['name'];
$data = file("data.txt");
if (in_array($post, $data)) {
echo "$post is checking in...";
}
else {
echo "Adding to $data...";
$data = fopen("data.txt", "a+");
fwrite($data, $post.PHP_EOL);
fclose($data);
}
$data = file("data.txt");
foreach ($data as $d) {
echo $d;
}
?>
</body>
</html>
tclient.html
<html>
<body>
<form action="test4.php" method="POST">
Name: <input type="text" name="name"><br>
<input type="submit">
</form>
</body>
</html>
data.txt
Names
John
Doe
The value in $post probably doesn't have a new line at the end. You can specify not to include new lines when you use file().
file("data.txt", FILE_IGNORE_NEW_LINES);
I was trying to follow the tutorials found on: https://www.ibm.com/developerworks/xml/library/x-phpwikipedia/index.html
All tutorials use Zend framework. I was wondering how this code can be adapted to avoid the use of Zend (or any other prerequisites) if possible? Please see example below. Thanks.
<?php
// load Zend classes
require_once 'Zend/Loader.php';
Zend_Loader::loadClass('Zend_Rest_Client');
// define category prefix
$prefix = 'hollywood';
try {
// initialize REST client
$wikipedia = new Zend_Rest_Client('http://en.wikipedia.org/w/api.php');
// set query parameters
$wikipedia->action('query');
$wikipedia->list('allcategories');
$wikipedia->acprefix($prefix);
$wikipedia->format('xml');
// perform request
// iterate over XML result set
$result = $wikipedia->get();
} catch (Exception $e) {
die('ERROR: ' . $e->getMessage());
}
?>
<html>
<head></head>
<body>
<h2>Search results for categories starting with
'<?php echo $prefix; ?>'</h2>
<ol>
<?php foreach ($result->query->allcategories->c as $c): ?>
<li><a href="http://www.wikipedia.org/wiki/Category:
<?php echo $c; ?>"><?php echo $c; ?></a></li>
<?php endforeach; ?>
</ol>
</body>
</html>
Something like this should work:
<?php
$prefix = 'allcategories';
$url = "http://en.wikipedia.org/w/api.php?action=query&list={$prefix}&format=json&continue=";
$res = file_get_contents($url);
$data = json_decode($res);
?>
<html>
<head></head>
<body>
<h2>Search results for categories starting with
'<?php echo $prefix; ?>'</h2>
<ol>
<?php foreach ($data->query->allcategories as $c):
?>
<li><?php echo $c->{'*'}; ?></li>
<?php endforeach; ?>
</ol>
</body>
</html>
In this case request will be using json format, its easier to live with :)
As the IBM article mentions, the Wiki API by default returns results in XML but can also return results in JSON, WDDX, YAML, or PHP serialized.
Basically, you just need to make an HTTP request that requests the correct information and parses the returned results. For example click this link http://en.wikipedia.org/w/api.php?action=query&list=allcategories&acprop=size%20&acprefix=hollywood&format=xml and you see it returns XML results in the browser which you can pretty much use any language to loop over and parse.
To request the contents of the xml data in PHP you could use something file_get_contents($target_url); and then you wouldn't have to rely on creating a zend rest client.
I'm saving a JSON string to a file and trying to read it back. For some reason it won't read it back. jsonlint.com is telling me it is a valid JSON.
Here is the JSON string:
{"userdef":{"vlan10":{"dfault":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"876"}},"upsell":{"down":{"rate":"876","ceil":"876"},"up":{"rate":"876","ceil":"76"}}},"br0":{"dfault":{"down":{"rate":"798","ceil":"987"},"up":{"rate":"987","ceil":"987"}},"upsell":{"down":{"rate":"98","ceil":"987"},"up":{"rate":"987","ceil":"89"}}},"br1":{"dfault":{"down":{"rate":"3","ceil":"654"},"up":{"rate":"654","ceil":"63"}},"upsell":{"down":{"rate":"65","ceil":"4"},"up":{"rate":"646","ceil":"5"}}},"eth3":{"dfault":{"down":{"rate":"65","ceil":"7876"},"up":{"rate":"7657","ceil":"5"}},"upsell":{"down":{"rate":"7865","ceil":"7"},"up":{"rate":"7","ceil":"5"}}}}}
Here is javascript/php code:
<?
if (file_exists('/tmp/qosconfig.conf'))
{
?>
var config = jQuery.parseJSON('<?=file_get_contents("/tmp/qosconfig.conf");?>');
<?
}
?>
This is a rather odd way of doing this. If you have the JSON string available to you in PHP, you can output it into the javascript as an object literal which saves the parsing step.
<?
if (file_exists('/tmp/qosconfig.conf')) {
$json = file_get_contents('/tmp/qosconfig.conf');
?>
var config = <?php echo $json; ?>;
<?
}
?>