I am using the insert PHP plugin for wordpress to get API data into my pages.
so I would replace "" on the last line with "[/insert_php]".
my code
[insert_php]
$url = 'https://www.eobot.com/api.aspx?idspeed=285967&json=true';
$args = array (
'method' => 'GET'
);
$response = wp_remote_request($url, $args);
$body = wp_remote_retrieve_body($response);
print_r($body);
[/insert_php]
returns
MiningSHA-256:0.00000000;MiningScrypt:0.00000000;CloudSHA-256:12.72592330;Cloud2SHA-256:0.01894240;CloudScrypt:0.00000000;
I have searched, and maybe I am not using the correct terms, and cannot find my solution or answer. I feel like it should be a lot easier than it is. I feel I should be able to take the array from the body and give each its own variable then use the variables to build a table with PHP. Where am I going wrong? Should I first store this in a php file on my server then create a table, then use the insert php function to build the table that way?
I have tried your code and its working fine for me in local mechine i think you just need to put json_decode for get proper format.
[insert_php]
$url = 'https://www.eobot.com/api.aspx?idspeed=285967&json=true';
$args = array (
'method' => 'GET'
);
$response = wp_remote_request($url, $args);
$body = wp_remote_retrieve_body($response);
print_r($body);
echo "<pre>";
$data = json_decode($body);
print_r($data);
[/insert_php]
Getting this type of output.
stdClass Object
(
[MiningSHA-256] => 0.00000000
[MiningScrypt] => 0.00000000
[CloudSHA-256] => 12.72656020
[Cloud2SHA-256] => 0.01894240
[CloudScrypt] => 0.00000000
)
Please try above code and let me know.
I've checked the code and it is doing what you programmed it do. Please check you're using correct API URL and once you're using the correct API URL use json_decode function to decode json data returned API and add once you've correct data converted into array, you can create table.
For example:
<?php
$body = wp_remote_retrieve_body($response);
$table_data = json_decode($body);
$html = array();
if(!empty($table_data)){
$html[] = '<table>';
foreach($table_data as $rows){
$html[] = '<tr>';
foreach($row as $column){
$html[] = '<td>'. $column . '</td>';
}
$html[] = '</tr>';
}
$html ='</table>';
}
$html = implode("\n", $html);
echo $html;
?>
PS: This code is only an example, please adjust it your data.
Related
I have a sample JSON Array labeled sample.txt that is sent from a sweepstakes form that captures a user's name and e-mail. I'm using WooBox so the JSON Array sends information over by each entry, so there are two entries here: http://pastebin.ca/3409546
On a previous question, I was told to break the ][ so that JSON_ENCODE can figure the separate entries. I would like to capture just the name and e-mail and import the array to my e-mail database (campaign monitor).
My question is: How do I add JSON variable labels to an array? If you see my code, I have tried to use the label $email. Is this the correct form or should it be email[0] with a for loop?
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$json = json_decode($content,true);
$tmp = explode('][', $json_string);
if (!count($tmp)) {
$json = json_decode($json_string);
var_dump($json);
} else {
foreach ($tmp as $json_part) {
$json = json_decode('['.rtrim(ltrim($json_string, '['), ']').']');
var_dump($json);
}
}
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array(
'api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$result = $wrap->add($json(
'EmailAddress' => $email,
'Name' => $custom_3_first,
'Resubscribe' => false
));
https://github.com/campaignmonitor/createsend-php/blob/master/samples/subscriber/add.php
This should have been fairly easy: if you have a JSON string and you call json_decode($string, true) on it, you get its equivalent in a PHP variable, plain and simple. From there, you can access it like you would any PHP array, object, etc.
The problem is, you don't have a proper JSON string. You have a string that looks like JSON, but isn't valid JSON. Run it through a linter and you'll see what I mean.
PHP doesn't know what to do with your supposed JSON, so you have to resort to manual parsing, which is not a path I would recommend. Still, you were almost there.
require_once 'csrest_general.php';
require_once 'csrest_subscribers.php';
$auth = array('api_key' => 'xxxxxxxxxxxxxxx');
$wrap = new CS_REST_Subscribers('xxxxxxxxxx', $auth);
$url = 'http://www.mywebsite.com/sweeps/test.txt';
$content = file_get_contents($url);
$tmp = explode('][', $content);
foreach ($tmp as $json_part) {
$user = json_decode('['.rtrim(ltrim($json_string, '['), ']').']', true);
$result = $wrap->add(array(
'EmailAddress' => $user->email,
'Name' => $user->fullname,
'Resubscribe' => true
));
}
I am trying to fetch the image which is already in parse database. In array I am getting the all the fetched data including the image URL but when I am trying to echo that particular URL it is echoing blank!!
Bellow is the code
$object = new ParseQuery("billComputing");
$getdata=$object->descending("updatedAt");
$results = $object->find();
$data=$results[0];
echo "<pre>";
print_r($results);
echo "signature".$sign=$data->get('Signature["url"]');
In print_r() - I am getting this
[Signature] => Parse\ParseFile Object
(
[name:Parse\ParseFile:private] => tfss-8a4dbd13-7e16-4efc-abcf-08e901924f49-sign
[url:Parse\ParseFile:private] => http://files.parsetfss.com/864d47af-9eac-4b75-ae30-17b7352d16ca/tfss-8a4dbd13-7e16-4efc-abcf-08e901924f49-sign
[data:Parse\ParseFile:private] =>
[mimeType:Parse\ParseFile:private] =>
)
I am not able to display the URL. Appreciate help in advance.
Try this :
$object = new ParseQuery("billComputing");
$getdata=$object->descending("updatedAt");
$results = $object->find();
$data=$results[0];
echo "<pre>";
print_r($results);
$file = $data->get('imageColumnName');
$imageURL = $file->getURL();
// you will get image url in $imageURL variable.
Here is my PHP/JSON code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$json=str_replace('},
]',"}
]",$json);
$decoded= json_decode($json);
$data=$decoded->matches[0];
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
Now I have the following problem
Notice: Trying to get property of non-object
and
Notice: Undefined property: stdClass::$team1
I just want use foreach loop and then show my results in HTML.
Why I am getting the 2 mentioned problems and how can I show the correct results?
Ok so the url your are using return VALID JSON, no need to change any of it!
I suggest using arrays, it has always appeared simpler to me
Do you want the logo_url from team or image_url from league? I will show both in my implementation.
So here is some corrected code
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
//I am not sure which one you want!!!
echo $value['league']['image_url'] . "<br>";
echo $value['team1']['logo_url'] . "<br>";
echo $value['team2']['logo_url'] . "<br>";
}
*EDIT To show wanted implementation by questions author...
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded= json_decode($json,true); // True turns it into an array
$data = $decoded['matches'];
foreach ($data as $value) {
echo "
<img src=\"http://dailydota2.com/{$value['team1']['logo_url']}\">
<img src=\"http://dailydota2.com/{$value['team2']['logo_url']}\">
";
}
I have checked your code and have some notes and hopefully a solution:
1- You are trying to get non existing key from JSON data, that is the message telling you.
2- I am still not sure what do you get from the JSON API. But regarding to dailydota2 documentation there is nothing called image_url under team1. I guess you are looking for logo_url or something like that.
3- Do not change the format of JSON as you do in your code, therefore delete following line:
$json=str_replace('}, ]',"} ]",$json);
Just leave the main JSON output from API as default.
4- When you try to get specific key from the decoded JSON/Array just use following way:
$data = $decoded->{'matches'};
in stead of
$data=$decoded->matches[0];
Reference: http://php.net/manual/en/function.json-decode.php
5- And finally your foreach loop is working but needs the correct key:
foreach ($data as $value) {
print_r($value->team1->logo_url);
}
When all these step is done, it should works.
Here is your final corrected code:
$json_url = "http://dailydota2.com/match-api";
$json = file_get_contents($json_url);
$decoded = json_decode($json);
$data = $decoded->{'matches'};
foreach ($data as $value) {
print_r($value->team1->logo_url);
echo '<img src="http://dailydota2.com/' . $value->team1->logo_url . '">';
}
It returns following output, and I do not get any errors.
/images/logos/teams/cdecgaming.png/images/logos/teams/teamempire.png
/images/logos/teams/ehome.png/images/logos/teams/ehome.png
/images/logos/teams/fnatic.png/images/logos/teams/cloud9.png
/images/logos/teams/teamissecret.png/images/logos/teams/teamissecret.png
/images/logos/teams/natusvincere.png/images/logos/teams/fnatic.png
Again I really do not know which information you want to get from the API but here you have a base of working code that you can work further with to get the required data from the right KEYs.
I have probably spent all day trying to figure this out. I have read multiple questions here on stack and also have been reading articles and checking on documentation, but I can't seem to figure out why this batch of code just produces a null output. Am I missing brackets, calling something wrong, ect?
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
refresh_requency => 30
);
echo json_encode($array);
?>
Again what I'm asking is can someone point out to me or tell me what I'm doing wrong. Is it my server that's just not handling the data correctly? That could be a possibility.
One other thing I've tried is to just print out $temp and/or the other variable like $str. When I do that though they don't even show up so that's what I think my problem is just not sure how to fix it.
Update
I've come to the conclusion that it's my web hosting service. As if I add var_dump($json) I get a null output null output.
Also to confirm that its my webhost if I run error_reporting(E_ALL); ini_set('display_errors', 1); it points to the file php.ini not allowing outgoing connections. I edited that same file on my local home server(raspberry pi) ran the same file and it works fine.
Below is the working solution for your above code:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
When I executed your code, I found 2 problem into your code snippet:
1) You were trying to use object of type stdClass as array.
Solution:
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str);
$temp = $json->main->temp_min;
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
?>
2) You did not put array key into quotes:
$array = array(
"content" => $content,
refresh_requency => 30
);
It should be :
$array = array(
"content" => $content,
"refresh_requency" => 30
);
Access $temp like this
$temp = $json->main->temp_min;
you will get the desired output.
Also, you need to allow allow_url_fopen in your php.ini config file. Some hosts disallow it for security reasons
$json = json_decode($str, true);
You need second argument to convert json string into associative array instead of the object. And you are trying to use array ($json['main']['temp_min']), not object. Also
$array = array(
"content" => $content,
"refresh_requency" => 30
);
The code looks like
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$content = $json['main']['temp_min'];
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
And result is http://codepad.viper-7.com/euBNAk :
{"content":44.6,"refresh_requency":30}
The second parameter of json_decode() is assoc (associative). By default it is 0. When it is 0 (default) the json_decode() will return an object, not an array. That's why you are unable to access temp_min by using $json['main']['temp_min'];
However If you use with the value 1 as second parameter, the function will return an array. Parameter 1 means setting associative to 1 (true). So use $json = json_decode($str, true); instead of $json = json_decode($str);. You will be able to access with $json['main']['temp_min']; now.
Also you forgot double quote on line 13 (refresh_requency). Goodluck.
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, true);
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30
);
echo json_encode($array);
Just want help
I change your code like this and that be correctly
<?php
$url = "http://api.openweathermap.org/data/2.5/weather?id=4879890&units=imperial";
$str = file_get_contents($url);
$json = json_decode($str, TRUE); // Wrong here
$temp = $json['main']['temp_min'];
$content = $temp;
$array = array(
"content" => $content,
"refresh_requency" => 30 // And wrong here, it's must string
);
echo json_encode($array);
?>
More information about json decode in php to array or object http://php.net/manual/en/function.json-decode.php
I would like to be able to extract a title and description from Wikipedia using json. So... wikipedia isn't my problem, I'm new to json and would like to know how to use it. Now I know there are hundreds of tutorials, but I've been working for hours and it just doesn't display anything, heres my code:
<?php
$url="http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$pageid = $data->query->pageids;
echo $data->query->pages->$pageid->title;
?>
Just so it easier to click:
http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids
I know I've probably just done a tiny thing wrong, but its really bugging me, and the code... I'm used to using xml, and I have pretty much just made the switch, so can you explain it a bit for me and for future visitors, because I'm very confused... Anything you need that I haven't said, just comment it, im sure I can get it, and thanks, in advance!
$pageid was returning an array with one element. If you only want to get the fist one, you should do this:
$pageid = $data->query->pageids[0];
You were probably getting this warning:
Array to string conversion
Full code:
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
echo $data->query->pages->$pageid->title;
I'd do it like this. It supports there being multiple pages in the same call.
$url = "http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$titles = array();
foreach ($data['query']['pages'] as $page) {
$titles[] = $page['title'];
}
var_dump($titles);
/* var_dump returns
array(1) {
[0]=>
string(6) "Google"
}
*/
Try this it will help you 💯%
This code is to extract title and description with the help of Wikipedia api from Wikipedia
<?php
$url = 'http://en.wikipedia.org/w/api.php?action=query&prop=extracts|info&exintro&titles=google&format=json&explaintext&redirects&inprop=url&indexpageids';
$json = file_get_contents($url);
$data = json_decode($json);
$pageid = $data->query->pageids[0];
$title = $data->query->pages->$pageid->title;
echo "<b>Title:</b> ".$title."<br>";
$string=$data->query->pages->$pageid->extract;
// to short the length of the string
$description = mb_strimwidth($string, 0, 322, '...');
// if you don't want to trim the text use this
/*
echo "<b>Description:</b> ".$string;
*/
echo "<b>Description:</b> ".$description;
?>