I am trying to bring in some API data to a directory in wordpress.
The data I am trying to get is just crypto coin price, none of the other information but because its format is sort of nested (?) it doesnt seem to work.
{
"bitcoin": {
"usd": 16808.82
}
}
This is my code so far:
<?php
$handle = curl_init();
$url = get_post_meta($entity-\>post()-\>ID, '\_drts_field_004', true);
// Set the url
curl_setopt($handle, CURLOPT_URL, $url);
// Set the result output to be a string.
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, false);
$output = curl_exec($handle);
curl_close($handle);
$data = json_decode($output);
echo $output;
var_dump($data);
The results are:
{
"bitcoin":{
"usd":16833.02
}
}
object(stdClass)#10399 (1) {
["bitcoin"]=> object(stdClass)#10492 (1) {
["usd"]=> float(16833.02)
}
}
In this example I am only after the 16833.02
I am trying to do this for lots of different coins, the "usd" will always be the same but the "bitcoin" will change when other coins.
How can I echo only the number?
I have tried lots of variations of echo but cannot get it? Is it possible to do something like:
echo $data['bitcoin']['usd'];
but rather than bitcoin use * ?
As in anything can be there?
You can access the usd value by decoding the JSON to an array instead of an object like this
$data = json_decode($output, true);
$usd = current($data)['usd'];
I have a list of Facebook links in xls sheet with Facebook id something like this
and when i go through these links means if i access Facebook with id www.facebook.com/7500
i get urls something like this https://www.facebook.com/davesachs/
so my question is i want to do this with PHP, i have a PHP page which read data from xls sheet
my code here:
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
echo $data[0].'<br>';
}
} else {
echo SimpleXLSX::parseError();
}
its returning all Facebook link with id same that i am passing like www.facebook.com/7500 but i want it return URL / link of profile as https://www.facebook.com/davesachs/ ,if it is possible please help me to do that.
You can do something like that, Taken reference from here
<?php
require_once 'src/SimpleXLSX.php';
if ( $xlsx = SimpleXLSX::parse('fburl.xlsx') ) {
$rows= $xlsx->rows();
foreach($rows as $data){
getRedirectedUrl($data[0]);
}
} else {
echo SimpleXLSX::parseError();
}
function getRedirectedUrl($link){
$url=$link;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // Must be set to true so that PHP follows any "Location:" header
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$a = curl_exec($ch); // $a will contain all headers
$url = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL); // This is what you need, it will return you the last effective URL
// Uncomment to see all headers
/*
echo "<pre>";
print_r($a);echo"<br>";
echo "</pre>";
*/
echo $url; // Voila
}
?>
This question already has an answer here:
How to extract and access data from JSON with PHP?
(1 answer)
Closed 4 years ago.
I am using the following code to pull data from an API with JSON results.
// Open connection
$ch = curl_init();
// Make the curl call
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$head = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$data = json_decode($head,true);
foreach($data as $item) {
$name = $item['name'];
$description = $item['description'];
echo "NAME: $name DESCRIPTION: $description";
}
If I use print_r($head) I see all of the results so I know url, username, password is good, however the echo statement at the end of the code is not producing results.
Here is a sample of what the JSON looks like when I print_r($head). Some of it at least.
{"events":[{"eventId":5183191,"name":"The Rhythm Rockets - FREE","description":"Summer Concert Series - The Rhythm Rockets . .\nFREE. Look for a YELLOW balloon. Bring a chair. PLEASE BE ON TIME (6:00 PM!) TO SIT WITH THE GROUP. Allow time for street parking. Expect a crowd. Meetup at 6pm - Showtime is 7pm. Food, wine and beer will be on sale.\nIn case of inclement weather, concerts will be held indoors at the Lincoln Center, 935 Maple Avenue. For weather updates, call[masked] after 5:30 pm. If moved inside, there is no way we can sit together.","primaryImage":{"smallImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.small.png","mediumImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.medium.png","largeImageUrl":"https://domainnamestorage.blob.core.windows.net/portalimages/portalimages/71021444-d72d-456c-a419-36b61ead5259.large.png"},"categories":[{"categoryId":2,"parentCategoryId":null,"name":"Performing Arts"},{"categoryId":12,"parentCategoryId":null,"name":"Food & Drink"},{"categoryId":17,"parentCategoryId":2,"name":"Music"},{"categoryId":75,"parentCategoryId":12,"name":"Drinks"},{"categoryId":100,"parentCategoryId":17,"name":"Concerts"}],"location":{"latitude":41.792683,"longitude":-88.011765,"city":"Downers Grove","state":"IL","address":"1000 Grove St","country":"United States","locationName":"Fishel Park"},"instances":[{"startDateTime":"2018-08-21T18:00:00Z","endDateTime":null,"hasTime":true,"allDay":false}],"price":{"lowerPrice":null,"upperPrice":null,"free":false,"description":null},"lastUpdatedDate":"2018-07-26T02:20:49.686Z","popularity":null,"interest":50,"links":[{"isSponsor":false,"name":"Meetup","linkUrl":"https://www.meetup.com/Im-Not-Dead-Yet-50-plus/events/252406255/","logoUrl":null},{"isSponsor":true,"name":"I'm Not Dead Yet --- 50+ Meetup","linkUrl":"http://Meetup.com/Im-Not-Dead-Yet-50-plus","logoUrl":null},{"isSponsor":true,"name":"I'm Not Dead Yet --- 50+ Meetup","linkUrl":"http://Meetup.com/Im-Not-Dead-Yet-50-plus","logoUrl":null}],"previousEventIds":[],"seriesStart":"2018-08-21T18:00:00Z","seriesEnd":null,"url":"http://portal.domainname.com/m/FireVite#!/details/THE-RHYTHM-ROCKETS-FREE/5183191/2018-08-21T18","handPicked":false,"customField":null,"contact":{"organization":null,"name":null,"email":null,"phone":null},"media":null}
After your decode, $data will have an array called events with each element being the array you are trying to look at. try:
foreach ($data['events'] as $item)...
print_r() does not make sense forstring, but only for array and object.
it might be rather alike this (and maybe you have to use $data['events'] instead)
when using $data = json_decode($response); it would be $data->events:
$data = json_decode($response, true);
// die('<pre>'.print_r($data, true).'</pre>');
foreach($data['events'] as $key => $item) {
// $event_id = $data['events'][$key]['eventId'];
$event_id = $item['eventId'];
// $name = $data['events'][$key]['name'];
$name = $item['name'];
// $desc = $data['events'][$key]['description'];
$desc = $item['description'];
echo "KEY: $key, ID: $event_id, NAME: $name, DESCRIPTION: $desc";
}
those inline comments just indicate, what is actually being accessed.
Hello guys i started to try use Steam API and i already done login... but i have a big problem to get items. I cant find solution what im doing wrong.
$GetClientSteamItemsUrl = " http://steamcommunity.com/profiles/" . $_SESSION['steam_steamid'] . "/inventory/json/730/2";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $GetClientSteamItemsUrl);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 3);
$output = curl_exec($ch);
$ArrayInventory = json_decode($output, true);
foreach($ArrayInventory['rgDescriptions'] as $inventory)
{
echo $inventory;
}
On that link is my items that i want to write their name on my page.
Error: Warning: Invalid argument supplied for foreach() in /data/web/virtuals/112855/virtual/www/subdom/ayy/index.php
Can someone help me to select specific part of code?
Try this
$inventory = file_get_contents("http://steamcommunity.com/profiles/".$_SESSION['steamid']."/inventory/json/730/2");
$myarrayInv = json_decode($inventory, true);
foreach($myarrayInv['rgDescriptions'] as $item)
{
echo $item['name'];
}
if you want icon_url etc. do $item['icon_url'], hope this helps.
I'm trying to convert this PHP cURL function to work with my rails app. The piece of code is from an SMS payment gateway that needs to verify the POST paramters. Since I'm a big PHP noob I have no idea how to handle this problem.
$verify_url = 'http://smsgatewayadress';
$fields = '';
$d = array(
'merchant_ID' => $_POST['merchant_ID'],
'local_ID' => $_POST['local_ID'],
'total' => $_POST['total'],
'ipn_verify' => $_POST['ipn_verify'],
'timeout' => 10,
);
foreach ($d as $k => $v)
{
$fields .= $k . "=" . urlencode($v) . "&";
}
$fields = substr($fields, 0, strlen($fields)-1);
$ch = curl_init($verify_url); //this initiates a HTTP connection to $verify_url, the connection headers will be stored in $ch
curl_setopt($ch, CURLOPT_POST, 1); //sets the delivery method as POST
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields); //The data that is being sent via POST. From what I can see the cURL lib sends them as a string that is built in the foreach loop above
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); //This verifies if the target url sends a redirect header and if it does cURL follows that link
curl_setopt($ch, CURLOPT_HEADER, 0); //This ignores the headers from the answer
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //This specifies that the curl_exec function below must return the result to the accesed URL
$result = curl_exec($ch); //It ransfers the data via POST to the URL, it gets read and returns the result
if ($result == true)
{
//confirmed
$can_download = true;
}
else
{
//failed
$can_download = false;
}
}
if (strpos($_SERVER['REQUEST_URI'], 'ipn.php'))
echo $can_download ? '1' : '0'; //we tell the sms sever that we processed the request
I've googled a cURL lib counterpart in Rails and found a ton of options but none that I could understand and use in the same way this script does.
If anyone could give me a hand with converting this script from php to ruby it would be greatly appreciated.
The most direct approach might be to use the Ruby curb library, which is the most straightforward wrapper for cURL. A lot of the options in Curl::Easy map directly to what you have here. A basis might be:
url = "http://smsgatewayadress/"
Curl::Easy.http_post(url,
Curl::PostField.content('merchant_ID', params[:merchant_ID]),
# ...
)