I am trying to use a weather API for a project and I am trying to build a simple weather app that will check the forecast and display it. The code looks like this:
$url = "http://api.openweathermap.org/data/2.5/weather?zip=30553&appid={APIKEY}";
$data = file_get_contents($url);
$decodeJSON = json_decode($data);
$testvar = "weather[0]->main";
echo $decodeJSON->$testvar;
and ideally I would like to be able to change $testvar to point at different variables returned by the API and as of right now I know it can't be done by combining "$decodeJSON->" and "$testvar", but is there anyway to achieve something close to what I have above that basically just assembles the two?
Appreciate all the help in advance and any feedback on the code is greatly appreciated!
I am trying to receive JSON data from an external system, and then process and save to my local DB. When an event triggers, the external system sends the data below to my system.
The external system logs show:
Log 1: Date/Time: 16 August 2017 11:54:44 AM
Status: Failure
Server: Apache https://blahblah.com/abc/data.php
Status Code: OK
Event Content: [{"field":"_USERNAME","value":""},
{"field":"_PASSWORD","value":""},
{"field":"_TOKEN","value":""},
{"field":"_CODE","value":"L77H4XD6ZA"},
{"field":"_SUBMITTEDDATE","value":"2017.08.16.01.54"},
{"field":"_SUBMITTEDDATEEXT","value":"2017.08.16.01.54.39.610"},
{"field":"_EDITEDDATE","value":"2017.08.16.01.55"},
{"field":"_SEQUENTIALID","value":"39a1cad9-2582-e711-9477-06c7814985cc"},
{"field":"_COMPLETETYPE","value":"Complete"},
{"field":"_LANGUAGE","value":"en"},
{"field":"_TOTALTIME","value":"12.59"},{"field":"_LINKURL","value":"http%3a%2f%2fsurv.blah.com%2ftest3%3fusr%3dL77H4XD6ZA"},
{"field":"GENDER","value":"TEXT%3aFemale%3bVALUE%3a2"},
{"field":"AGE","value":"TEXT%3a40%2b-%2b44%3bVALUE%3a6"},
{"field":"STATE","value":"TEXT%3aVIC%3bVALUE%3a2"},
{"field":"END_CHC","value":"TEXT%3aComplete%3bVALUE%3a2"},
{"field":"D2H","value":""},
{"field":"D2V","value":""},
{"field":"PCODE","value":""},
{"field":"PSTATE","value":""},
{"field":"PREGION","value":""},
{"field":"STATEREGION","value":""},
{"field":"TEST1","value":""}]
So, in my php file (https://blahblah.com/abc/data.php) I have
$json = file_get_contents('php://input');
$obj = json_decode($json);
and I have been trying a foreach() loop to try and get each field and value, to then put into a database, like
foreach($obj as $key => $value)
{
$qry = $conn->prepare('INSERT INTO `key_value`(`db_id`, `rkey`, `rvalue`) VALUES (NULL,$key,$value)');
$qry->execute();
}
But it isn't working, and I either get errors about the foreach loop, or if I play around with just echoing or var_dumping, I get NULL in the response, when I use the Postman or ARC Chrome API testing Apps.
So, I suspect I am on the completely wrong track of how to do this.
Can anyone help guide me back?
EDIT: I have had a look at Receive JSON POST with PHP and a few others, but the working answers aren't clear.
You've got a couple of problems here. First, you need to pass true as the second parameter to json_decode in order to get an associative array instead of a stdClass. Then, when you're iterating the results, you don't need the $key, and the $value is each entry in the results array (each "row"). Try running this to see what's going on:
<?php
$json = <<<JSON
[{"field":"_USERNAME","value":""},
{"field":"_PASSWORD","value":""},
{"field":"_TOKEN","value":""},
{"field":"_CODE","value":"L77H4XD6ZA"},
{"field":"_SUBMITTEDDATE","value":"2017.08.16.01.54"},
{"field":"_SUBMITTEDDATEEXT","value":"2017.08.16.01.54.39.610"},
{"field":"_EDITEDDATE","value":"2017.08.16.01.55"},
{"field":"_SEQUENTIALID","value":"39a1cad9-2582-e711-9477-06c7814985cc"},
{"field":"_COMPLETETYPE","value":"Complete"},
{"field":"_LANGUAGE","value":"en"},
{"field":"_TOTALTIME","value":"12.59"},{"field":"_LINKURL","value":"http%3a%2f%2fsurv.blah.com%2ftest3%3fusr%3dL77H4XD6ZA"},
{"field":"GENDER","value":"TEXT%3aFemale%3bVALUE%3a2"},
{"field":"AGE","value":"TEXT%3a40%2b-%2b44%3bVALUE%3a6"},
{"field":"STATE","value":"TEXT%3aVIC%3bVALUE%3a2"},
{"field":"END_CHC","value":"TEXT%3aComplete%3bVALUE%3a2"},
{"field":"D2H","value":""},
{"field":"D2V","value":""},
{"field":"PCODE","value":""},
{"field":"PSTATE","value":""},
{"field":"PREGION","value":""},
{"field":"STATEREGION","value":""},
{"field":"TEST1","value":""}]
JSON;
$obj = json_decode($json, true);
foreach($obj as $currTuple)
{
echo $currTuple['field'].':'.urldecode($currTuple['value'])."\n";
}
Also some of the results are url encoded, so you'll probably want to decode that before persisting.
I am sorry to sound confusing but I will try to explain in the best way possible.
In the controller I have a function search
public function search(){
/*
I run my logics and get few URL from
where I need to fetch further data
the urls are saved in the URL array
$urls[0] = "http://url1.com/search1";
$urls[1] = "http://url2.com/search2";
I then set this in data variable and send it to view
so that It can be run in AJAX
I tired running get_file_contents but it executes
in series one after the other URL.
If there are 10 URL (5 secs per URL) the over all processing time
increases drastically
*/
$data["urls"] = $urls;
$resp = $this->load->view('ajaxer',$data,TRUE);
/* based on the $resp i need to run further business logic's */
}
Now the $resp is actually giving me only the HTML code. It is not executing the HTML and hence the ajax is not run.
Any thoughts on how to execute this will be really helpful.
Regards,
Amit
Your code is absolutelly ok. But your javascript is not getting any response data (only headers), because you are not returning any output.
If you want to "execute your HTML" you need to change the line with view to this:
$this->load->view('ajaxer',$data);
or this:
$resp = $this->load->view('ajaxer',$data,TRUE);
echo $resp;
You forgot to echo output in the controller. Apart from this you need few minor modification in your function.
public function search(){
/*
I run my logics and get few URL from
where I need to fetch further data
the urls are saved in the URL array
$urls[0] = "http://url1.com/search1";
$urls[1] = "http://url2.com/search2";
I then set this in data variable and send it to view
so that It can be run in AJAX
I tired running get_file_contents but it executes
in series one after the other URL.
If there are 10 URL (5 secs per URL) the over all processing time
increases drastically
*/
// You need to check either request came from Ajax request or not. If not it will echo passed string. It prevents to access this function besides Ajax request
if (!$this->input->is_ajax_request()) {
echo "Ajax Requests allowed.";
die;
}
$data["urls"] = $urls;
$resp = $this->load->view('ajaxer',$data,TRUE);
// Standard way to set response for output in json format.
// #param status will help to check all things goes correct or not. if not please pass false on the basis or your feature's requirement
$this->output->set_output(json_encode(array('status'=>true,'response'=>$resp)));
// Standard way to get output set above step.
$string = $this->output->get_output();
echo $string;
exit();
/* based on the $resp i need to run further business logic's */
}
Updated code is here. Hope you find your answer
I'm trying to build a little script that would let me do this:
http://example.com/appicons.php?id=284417350
and then display this in plain text
http://a3.mzstatic.com/us/r1000/005/Purple/2c/a0/b7/mzl.msucaqmg.png
This is the API query to get that information (artworkUrl512):
http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=284417350
Any help and example code would be much appreciated!
I am not sure why you have jQuery in your tags, unless you want to make the request dynamically without a page refresh. However you can do this simply in PHP using the following example:
$request = array (
"app_id" => #$_GET["id"]
);
// parse the requests.
if (empty($request["app_id"])) {
// redirects back / displays error
}
else {
$app_uri = "http://ax.itunes.apple.com/WebObjects/MZStoreServices.woa/wa/wsLookup?id=" . $request["app_id"];
$data = file_get_contents ($app_uri);
$json = json_decode (trim($data));
print($json->results[0]->artworkUrl100);
}
$request = file_get_contents($itms_url);
$json = json_decode(trim($request));
echo $json[0]->artworkUrl512;
should work in PHP. Unless of course there is more than one hit to the search. A solution using jQuery is probably not very much more difficult.
Hi I have a php srcript that receives GET data and I want to redirect the data from GET to another page in wordpress using POST. It's that possible, and how?
Thank's for the help.
The only way this could be done in pure PHP is by using cURL and printing the result of that request in the page:
<?php
// sort post data
$postarray = array();
foreach ($_GET as $getvar => $getval){
$postarray[] = $getvar.'='.urlencode($getval);
}
$poststring = implode('&',$postarray);
// fetch url
$curl = curl_init("http://www.yourdomain.com/yourpage.php");
curl_setopt($ch,CURLOPT_POST,count($postarray));
curl_setopt($ch,CURLOPT_POSTFIELDS,$poststring);
$data = curl_exec($curl);
curl_close($curl);
// print data
print $data;
?>
Obviously you'd validate the GET data before you post it.
If there's another way you can do this I'd be interested to know as this method is not ideal. Firstly, cURL must be enabled in PHP, and secondly there will be some overhead in requesting another URL.
Only using form and javascript, which is not bulletproof.