A remote site is supplying a data structure in a js file.
I can include this file in my page to access the data and display it in my page.
<head>
<script type="text/javascript" src="http://www.example.co.uk/includes/js/data.js"></script>
</head>
Does anyone know how I use PHP to take this data and store in it a database?
You should GET that file directly, via, for example, CURL. Then parse it, if it comes in JSON, you can use json-decode.
Simple example (slightly modified version of code found here):
<?php
$url = "http://www.example.co.uk/includes/js/data.js";
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
...
$output = curl_exec($ch);
$info = curl_getinfo($ch);
if ($output === false || $info['http_code'] != 200) {
$error = "No cURL data returned for $url [". $info['http_code']. "]";
if (curl_error($ch))
$error .= "\n". curl_error($ch);
}
else {
$js_data = json_decode($output);
// 'OK' status; save $class members in the database, or the $output directly,
// depending on what you want to actually do.
...
}
//Display $error or do something about it
?>
You can grab the file via CURL or some other HTTP downloading library/function. Then, parse the data. If you're lucky, the data is in a JSON format and you can use a PHP function to convert it into a PHP array. Then, iterate through the items in the array, inserting each into your database.
Related
I have been trying to send the xml response I have stored in '$kxml' variable to the 'kycresult.php' page. I want to fetch the values from that xml and just print it. I am able to fetch the values if I store the xml in txt file and then get it using 'simplexml_load_file' but I don't want to create an extra file. Please let me know if there is a way to send the $kxml on next page.
$kycch = curl_init();
curl_setopt($kycch, CURLOPT_URL, $csckua_url);
curl_setopt($kycch, CURLOPT_POSTFIELDS, $kycxml);
curl_setopt($kycch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($kycch, CURLOPT_TIMEOUT, 20);
$kycresult = curl_exec($kycch);
$curl_errno = curl_errno($kycch);
$curl_error = curl_error($kycch);
curl_close($kycch);
// echo $kycresult;
$kxml = simplexml_load_string($kycresult);
if ($kxml['ret'] == 'Y') {
// $ksuccess = 'Authentication Successful';
header('location:Kycresult.php');
} else {
$ksuccess = 'Authentication Failed';
}
As one of the possible solutions you can store the variable in session
session_start();
$_SESSION['kxml'] = $kxml;
Then on the next page it will be available through
$kxml = $_SESSION['kxml'];
But actually it still stores in the auxiliary file by default under the hood.
So I'm trying to make a simple API, I have tried lots of different things. I want to show a random number on my JSON object and a token to go with it, then store both in a database. I don't want this to happen when you visit the webpage I want the data to get sent to a DB and generated from a separate page.
The first step in this is getting data from a different file.
Here's what I tried first:
index.php:
<?php
$odds = rand(1, 100);
?>
<pre style="word-wrap: break-word; white-space: pre-wrap;">
{
"odds": <?php echo $odds;?>
}
</pre>
Here's the file I'm trying to get the data from:
<?php
$url = "https://flugscoding.com/random/";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, "Riverside API");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
if(!$response = curl_exec($ch)) {
echo curl_error($ch);
}
curl_close($ch);
$data = json_decode($response, true);
echo $data->odds;
?>
Error:
Notice: Trying to get property 'odds' of non-object in D:\xxamp\htdocs\random\perp.php on line 16
What I tried after:
index.php:
<?php
$values = array("odds"=>rand(1, 100));
echo json_encode($values);
?>
Here's the file I'm trying to get the data from:
<?php
$json = file_get_contents("index.php");
echo $json;
// echo $json->odds;
?>
Error:
It doesn't show any data or errors, just a blank screen.
Does anyone have any solutions to this problem? I'm trying to make a provably fair system for a friend.
You're really close in both your examples:
#1
$data = json_decode($response, true);
echo $data->odds;
You're passing true into json_decode which makes it an associative array, not an object. So you will need to get the odds with $data['odds']; instead.
#2
$json = file_get_contents("index.php");
echo $json;
file_get_contents can either fetch a local file or remote file. In this case, you're passing a local file, so $json is the contents of the PHP code.
You can either:
(a) redesign it so that index.php is a function, and you can call the function from different files
(b) call index.php remotely and parse the results
a. Create a function in index.php that can get the odds:
<?php
function getData() [
return array("odds"=>rand(1, 100));
}
Then, in another file, you can:
<?php
require_once 'index.php';
$data = getData(); //now you have access to $data['odds'];
b. Call index.php remotely, like this:
$json = file_get_contents("http://localhost/index.php");
print_r(json_decode($json, true));
I'm trying to load an xml file from another website. I can do this using cURL using the following:
function getLatestPlayerXML($par1) {
$url = "http://somewebsite/page.php?par1=".$par1;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$xmlresponse = curl_exec($ch);
$xml = simplexml_load_string($xmlresponse);
$xml->asXML("./userxml/".$par1.".xml");
return $xml;
}
This works all well and good, however, the external website takes a long time to respond with the file, which is why I save the xml file to ./userxml/$par1.xml which also works. I load like this:
function getLocalPlayerXML($par1) {
$xml = simplexml_load_file("./userxml/".$par1.".xml");
if($xml != False) {
// How can I make it so that when called it only temporarily uses this file until the latest is available?
return $xml;
} else {
return $getLatestPlayerXML($par1);
}
}
The problem I am having is that I want it so when I call a single load function it first tries to load the xml from file and if it exists use that file until the latest file has been received at which point, update the page. If the file does not exist, simply wait until the latest file has been retrieved and then use that. Is even possible?
How am i suppose to store the Hotel name and location from the response provided by google place api in PHP array. If my search string is restaurant in New York.
The response of the api is in json format.
My script for sending the search request is:
<?php
if(isset($_GET['text']))
{
if(!empty($_GET['text']))
{
$search_text=strip_tags($_GET['text']);
$hostname = "https://maps.googleapis.com/maps/api/place/textsearch/json?query=$search_text&sensor=true&key=AIzaSyDVdJtIAvhmHE7e2zoxA_Y9qWRpp6eE2o8";
// read the post from PayPal system and add 'cmd'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "$hostname");
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
$res = curl_exec($ch);
curl_close($ch);
if(!$res)
{
// error log
echo'Unable to find results.';
} else {
**// ALL output printing code goes down here**
//$res=json_decode($res);
//var_dump(json_decode($res));
$obj=var_dump(json_decode($res, true));
print_r($obj['"results']);
}
} else {
echo'<h4><font color="red">Please enter the text to search.</font></h4>';
}
}
?>
Well, the output of the above code is something in json format. But i need to retrieve the Name of the Restaurant and their location from the json output.
So, Please suggest me a way to extract the exact output.
As I can see the results key contains arrays with the data you need.
Just do something like:
$jsonContent = json_decode($res, true);
foreach ($jsonContent['results'] as $result) {
// now you have the $result array that contains the location of the place
// and the name ($result['formatted_address'], $result['name']) and other data.
}
I hope you know what to do from this point.
I am trying to display the data of a xml parsed page which i get from a external source. which i got passing through some parameters like this:-
http://www.somewebsite.com/phpfile.php?vendor_key=xxx&checkin=2012-11-02&checkout=2012-11-05&city_id=5&guests=3
when i pass this parameters i got an xml result. now i want to display that xml data in a designer way on my webpage. so how can i do so. i am new to xml so dont know what this technology called if any body can tell me what this called so that can also help me.
Take a look at simplexml_load_string.
You can use curl or file_get_contents function to make HTTP request. Then after you can use DOM or SimpleXML to parse the response (XML) of requested URL.
If u have already XMl then try
echo $xml->asXML();
A full example
<?php
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL, 'http://rss.news.yahoo.com/rss/topstories');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
print $item->title;
}