php loop to pull json data fields - php

Hello everyone and thanks for your time. I am trying to set up a loop to pull specific fields from a json api feed. The json feed can be seen here:
https://uysmiami.com/search/api_server_custom.php
I am trying to set up a loop to grab data from specific fields from the feed but with my limited php am grabbing other stuff as well. The results of my loop are can be seen at:
http://uysmiami.com/search/stevetest.php
the code I'm using is:
<?php
$json = file_get_contents('https://api.iyba.pro/vessel?key=95d30b94b3a7e8b8c2df379fb00816960f86e203&id=80393');
$data = json_decode($json,true );
foreach($data as $vdata)
{ foreach($vdata as $number){
echo "Name: ".$number['ListingOwnerName']."<br />";
} }
?>
how can I pull the fields I want and not the first two and last 4 lines of meaningless stuff?
Thanks again.

I got your desired results doing something like this:
$dataFromUrl = file_get_contents( 'https://uysmiami.com/search/api_server_custom.php' );
$dataEn = json_decode( $dataFromUrl, TRUE );
foreach( $dataEn['V-Data'] as $vData )
{
if ( isset( $vData['ListingOwnerName'] ) )
{
echo "Name: " . $vData['ListingOwnerName'] . "<br />";
}
}
I am not sure if you need to loop through more things which is why you nested another loop, but for the V-Data array from the API shown, that got all the names without any numbers.

Related

Accessing JSON array data in PHP

I am trying to get some data from an external API. From the JSON data I want to retrieve some data as marked in the image.
I can access the "teams" data by using this code -
foreach( $data->data as $info ) {
echo '<li class="team-1">'. $info->teams[0].'</li>';
echo '<li class="team-2">'. $info->teams[1].'</li>';
};
But when I try to access data more deep from array of objects it doesn't work & gives me error -
foreach( $info->sites as $site) {
foreach( $site->odds as $odd) {
echo $odd->h2h[0];
}
}
So my question is what is the best way to loop through the data to access these arrays. I am using this code in Wordpress but I think it will be same as PHP.
You should access h2h directly from odds, since it's not an array, but an object
foreach( $info->sites as $site) {
echo $site->odds->h2h[0];
}
It looks like odds is an object rather than an array.
If h2h will always be the only property in odds then you can try:
foreach( $info->sites as $site) {
echo $site->odds->h2h[0];
}
Alternatively, if h2h will not always be the only property in odds, then you may want to try casting it into an array:
foreach( $info->sites as $site) {
foreach( (array)$site->odds as $odd) {
echo $odd[0];
}
}
You get this json from an external api and convert it using json_decode, right? If that is so, just use the second parameter "$assoc" and set it to true to not get an object, but an associative array that you can use like this:
$info = json_decode($api_answer,true);
if(isset($info['sites']['odds'])){
foreach($info['sites']['odds'] as $odd){
echo $odd['h2h'][0]
}
}

Getting nested array data from JSON

I am currently trying to retrieve some info from some json code in PHP. I have some of it achieved but I am trying to get a players name from a nested array and I am having a bit of trouble. This is the json info:
Sorry I had to post on pastebin as JSON wouldnt embed in the code box. ht
tps://pastebin.com/6RZAgKFa
I have pulled in the info like so:
$json_string2 = 'URL TO JSON DATA';
$jsondata2 = file_get_contents($json_string2);
$serverinfo2 = json_decode($jsondata2,true);
And I can view it by printing it.
Now I am trying to loop through it all to just retrieve names, I am trying the following:
foreach($serverinfo2 as $playerinfo) {
foreach($playerinfo as $playerstuff) {
echo $playerstuff;
}
}
But that returns the full array. I then add [name] to the end of echo $playerstuff and it returns a number 1 and a D. Not even relevant, and $playerstuff->name also doesn't work. Can anyone help me at all. Thanks :)
You can try this to achieve data from nested data from json :
<?php
$res = '[{"endpoint":"127.0.0.1","id":"2","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Deadpool","ping":"85"},{"endpoint":"127.0.0.1","id":"1","identifiers":["STEAMID HERE","LICENSE HERE"],"name":"Logan","ping":"73"}]';
$result = json_decode($res,true);
// echo '<pre>'; //print_r($result);
foreach ($result as $key => $value) {
// print_r($value);
echo $endpoint = 'endpoint : ' .$value['endpoint'];echo "<br/>";
echo $name = 'name :' .$value['name'];echo "<br/>";
}
?>

Why is my variable variable not referencing the json data?

I have tried to understand and solve this issue to no end. I think I'm close in that I suspect I'm simply referencing my json data incorrectly, but I cannot figure out how to do it right. Here's the use case.
I'm building a simple ledger system to track crypto transactions. The system also does some nice tallying of coin totals, calculates coin values in USD, and caculates overall portfolio value etc.
I let the user track coins of their choice that sit in an array called $coins. The $coins array is initialized earlier in my code via a database call and contains $coin->ID and the $coin->symbol.
To determine coin values in USD, I make a call out to CryptoCompare using their API, which, after grabbing the coin symbols from my $coins array, looks something like this:
https://min-api.cryptocompare.com/data/pricemulti?fsyms=ADA,BTC,ETH,LTC&tsyms=USD
Just pop that URL into a browser to view the results set.
$price_request_data stores that data after being decoded.
Now my problem arises when I try to reference the JSON data via my $coins loop. I can reference the data just fine if I use a direct reference such as:
$price_request_data->BTC->USD
That produces a value of 15592.
But obviously I want to loop through my $coins loop and dynamically create variables for each coin to hold its respective price. When I try to reference the JSON data in this way, it fails to retrieve the price ( 15592) and instead returns 0.
// ----------------------------------------------------------
// GET CURRENT PRICES
$apiurl = "https://min-api.cryptocompare.com/data/pricemulti?fsyms=ADA,BTC,ETH,LTC&tsyms=USD";
$price_request = wp_remote_get( $apiurl );
if( is_wp_error( $price_request ) ) {
return false;
}
$price_request_body = wp_remote_retrieve_body( $price_request );
$price_request_data = json_decode( $price_request_body );
if( ! empty( $price_request_data ) ) {
echo $price_request_data->BTC->USD . "<br />"; // PRODUCES 15592
foreach( $coins as $coin ) {
$pricereqdata = "price_request_data->" . $coin->symbol . "->USD";
echo $$pricereqdata; // PRODUCES 0
// Generate the variable name string i.e. "curpricebtc"
$curprice = "curprice" . strtolower( $coin->symbol );
// Format the current coin's price
$$curprice = number_format( ceil_dec( $$pricereqdata, 2 ), 2, ".", "" );
}
}
This is the vardump of $price_request_data:
object(stdClass)#1527 (4) {
["ADA"]=>
object(stdClass)#1528 (1) {
["USD"]=>
float(0.4469)
}
["BTC"]=>
object(stdClass)#1535 (1) {
["USD"]=>
float(15592)
}
["ETH"]=>
object(stdClass)#1536 (1) {
["USD"]=>
float(757.13)
}
["LTC"]=>
object(stdClass)#1539 (1) {
["USD"]=>
float(291.21)
}
}
I'm using PHP7 and I know some reference rules changed, but I was not able to determine if that's my issue. I swear it's just the way I'm referencing it with a variable variable, but I'm not experienced enough to know why.
Any wisdom is much appreciated.
OK:
Q: Does "$price_request_data" equal {"ADA":{"USD":0.4738},"BTC":{"USD":15486.46},"ETH":{"USD":786.47},"LTC":{"USD":306.48}} (or equivalent)?
<= Your comment, "// WORKS", implies "yes"
Q: Where is "$coin" initializated? What is its value?
Q: What is a value of "$pricereqdata"?
Q: Does "$$pricereqdata" create a new variable for you? What is it? What is its value?
In other words, exactly what do you mean by "// FAILS"???

How to get data from array [API/JSON]

I'm currently trying to get going with API's but i'm finding it really hard to extract the data from the api into my webpage.
I have tried using json_decode($, true), and it works OK, but some data I just cant extract.
Like, in this example, how would you get the name?
{"id":12345678,"name":"MyAwesomeLeagueName","profileIconId":593,"summonerLevel":30,"revisionDate":1389164617000}
I have used for getting data from others, but cant really get it to work with types like this one.
//put json in array
$r = json_decode($r, true);
echo $r['champions'][1]['attackRank'];
Also, if anyone have some good JSON -> PHP Tutorials I would really appreciate.
In that example to access the name you just need to refer to $r['name'] e.g.
echo $r['name'];
After decoding the JSON string, do a var_dump on your array and it will show you the contents and how to access.
To get all with a certain magic rank as per your example, you'd need to loop through the array and test the value of the particular key:
$r = json_decode($r, true);
//loop through $r
foreach ($r['champions'] as $key => $value) {
if ($value['magicRank'] != 8) {
//if magicRankis not 8, ignore and move on to the next entry
continue;
}
//magicRank is 8, do something
echo $value['name'] . " has magic rank of 8<br />";
}

Domain index checking using Google API

I am trying to build website where a user can enter his website and check his indexed pages in google.
Just like we do by site:domain.com
I am using a google API, here is the link to API (I know it's deprecated)
http://ajax.googleapis.com/ajax/services/search/web?v=1.0&q=
when I use a code like
<?php
function getGoogleCount($domain) {
$content = file_get_contents('http://ajax.googleapis.com/ajax/services/' .
'search/web?v=1.0&filter=0&q=site:' . urlencode($domain));
$data = json_decode($content);
return ($data->responseData->cursor->estimatedResultCount);
}
echo getGoogleCount('stackoverflow.com');
?>
good as far as I want to know about the result counts
But the next thing I want is to list all the results on my website. I am unable to grab the results because when we write
$data->responseData->cursor->estimatedResultCount
It goes straight
But when we try to get results. I don't know how to do, just to print the idea
$data->responseData->results->[url & title & content here]
Because here results is an array. and I don't know how can I store info in an array in this case.
Have been searching for a long time but can't find anything related.....
Thanks in advance...
The easiest way is to use:
$data = json_decode($content, true);
That will convert objects to normal associative arrays which are probably easier to handle.
Then you access your values by something like this:
$results = $data['responseData']['results']; //array
$googleCount = $data['responseData']['cursor']['estimatedResultCount'];
Then with the results you can do something like this:
foreach ($results as $result) {
echo $result['title'].' -> '.$result['url'] . '<br />';
}
But of course if you don't like associative arrays and you prefer objects, you could do it also this way:
$data = json_decode($content);
foreach ($data->responseData->results as $result) {
echo $result->title .' -> '.$result->url.'<br />';
}
If you want to check which properties has the $result, just use print_r or var_dump.

Categories