I got two php pages:
client.php and server.php
server.php is on my web server and what it does is open my amazon product page and get price data and serialize it and return it to client.php.
Now the problem I have is that server.php is getting the data, but when I return it and do echo after using unserialize(), it shows nothing. But if I do echo in server.php, it shows me all the data.
Why is this happening? Can anyone help me please?
This the code I have used:
client.php
$url = "http://www.myurl.com/iec/Server.php?asin=$asin&platform=$platform_variant";
$azn_data = file_get_contents($url);
$azn_data = unserialize($azn_data);
echo "\nReturned Data = $azn_data\n";
server.php
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
return($serialized_data);
}
else
{
echo "Warning: No Data Found!";
}
On server.php , you need to replace your following line:
return($serialized_data);
for this one:
echo $serialized_data;
because client.php reads the output of server.php, return is used to pass information from functions to caller code.
UPDATE:
Apart from the fixes above, you're hitting a bug in unserialize() function that presents with some special combination of characters, which your data seems to have, the solution is to workaround the bug by base64() encoding the data prior to passing it to serialize() , like this:
In client.php:
$azn_data = unserialize(base64_decode($azn_data));
In server.php:
echo base64_encode($serialized_data);
Source for this fix here .
You are not serializing your data on server side so there is nothing to deserialize on client side.
return(serialize($serialized_data));
Edit:
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
die(serialize($serialized_data));
}
else
{
echo "Warning: No Data Found!";
}
Related
I have the following code:
<?php
$json = file_get_contents("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
$decode = json_decode($json,true);
foreach($decode['data'] as $val){
echo date('Y-m-d',$val['date']).' -- '.$val['amount'].' -- '.$val['txHash'].' -- '.$val['confirmed'];
echo "<br/>";
}
The API used (nanopool) being extremely unreliable, I get a non empty json (success) every 2 to 10 calls.
I tried to loop the file_get_contents (do... while) until getting a non empty json without success. What can you recommend to loop until I get an answer?
Maybe you can try something like this, still I don't recommend using this within a synchronous script (eg a web page) because you can't control the time needed to get a successfull answer.
<?php
function getFileFTW($url)
{
$fuse = 10;//maximum attempts
$pause = 1;//time between 2 attempts
do {
if($fuse < 10)
sleep($pause);
$s = #file_get_contents($url);
}
while($s===false && $fuse--);
return $s;
}
$json = getFileFTW("https://api.nanopool.org/v1/eth/payments/0x218494b2284a5f165ff30d097d3d7a542ff0023B");
if($json) {
$decode = json_decode($json,true);
//...
}
else {
//json not loaded : handle error
}
My script is working most of the times, but in every 8th try or so I get an error. I'll try and explain this. This is the error I get (or similar):
{"gameName":"F1 2011","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/81163/movie_max.webm?t=1447354814","gameId":"44360","finalPrice":1499,"genres":"Racing"}
{"gameName":"Starscape","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/900679/movie_max.webm?t=1447351523","gameId":"20700","finalPrice":999,"genres":"Action"}
Warning: file_get_contents(http://store.steampowered.com/api/appdetails?appids=400160): failed to open stream: HTTP request failed! in C:\xampp\htdocs\GoStrap\game.php on line 19
{"gameName":"DRAGON: A Game About a Dragon","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/2038811/movie_max.webm?t=1447373449","gameId":"351150","finalPrice":599,"genres":"Adventure"}
{"gameName":"Monster Mash","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/900919/movie_max.webm?t=1447352342","gameId":"36210","finalPrice":449,"genres":"Casual"}
I'm making an application that fetches information on a random Steam game from the Steam store. It's quite simple.
The script takes a (somewhat) random ID from a text file (working for sure)
The ID is added to the ending of an URL for the API, and uses file_get_contents to fetch the file. It then decodes json. (might be the problem somehow)
Search for my specified data. Final price & movie webm is not always there, hence the if(!isset())
Decide final price and ship back to ajax on index.php
The error code above suggests that I get the data I need in 4 cases, and an error once. I only wanna receive ONE json string and return it, and only in-case $game['gameTrailer'] and $game['final_price'] is set.
This is the php (it's not great, be kind):
<?php
//Run the script on ajax call
if(isset($_POST)) {
fetchGame();
}
function fetchGame() {
$gameFound = false;
while(!$gameFound) {
////////// ID-picker //////////
$f_contents = file("steam.txt");
$url = $f_contents[mt_rand(0, count($f_contents) - 1)];
$answer = explode('/',$url);
$gameID = $answer[4];
$trimmed = trim($gameID);
////////// Fetch game //////////
$json = file_get_contents('http://store.steampowered.com/api/appdetails?appids='.$trimmed);
$game_json = json_decode($json, true);
if(!isset($game_json[$trimmed]['data']['movies'][0]['webm']['max']) || !isset($game_json[$trimmed]['data']['price_overview']['final'])) {
continue;
}
$gameFound = true;
////////// Store variables //////////
$game['gameName'] = $game_json[$trimmed]['data']['name'];
$game['gameTrailer'] = $game_json[$trimmed]['data']['movies'][0]['webm']['max'];
$game['gameId'] = $trimmed;
$game['free'] = $game_json[$trimmed]['data']['is_free'];
$game['price'] = $game_json[$trimmed]['data']['price_overview']['final'];
$game['genres'] = $game_json[$trimmed]['data']['genres'][0]['description'];
if ($game['free'] == TRUE) {
$game['final_price'] = "Free";
} elseif($game['free'] == FALSE || $game['final_price'] != NULL) {
$game['final_price'] = $game['price'];
} else {
$game['final_price'] = "-";
}
}
////////// Return to AJAX (index.php) //////////
echo
json_encode(array(
'gameName' => $game['gameName'],
'gameTrailer' => $game['gameTrailer'],
'gameId' => $game['gameId'],
'finalPrice' => $game['final_price'],
'genres' => $game['genres'],
))
;
}
?>
Any help will be appreciated. Like, are there obvious reason as to why this is happening? Is there a significantly better way? Why is it re-iterating itself at least 4 times when it seems to have fetched that data I need? Sorry if this post is long, just trying to be detailed with a lacking php/json-vocabulary.
Kind regards, John
EDIT:
Sometimes it returns no error, just multiple objects:
{"gameName":"Prime World: Defenders","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/2028642/movie_max.webm?t=1447357836","gameId":"235360","finalPrice":899,"genres":"Casual"}
{"gameName":"Grand Ages: Rome","gameTrailer":"http://cdn.akamai.steamstatic.com/steam/apps/5190/movie_max.webm?t=1447351683","gameId":"23450","finalPrice":999,"genres":"Simulation"}
So I have this program that allows a user to enter information into a form and upon submission turns that information into a JSON file. When a user goes to a different part of the program, the programs retrieves the JSON file and builds a questionnaire out of it.
The building of the JSON file works fine but whenever I try to retrieve the file I'm getting an error that the JSON is returning as ASCII and as NULL. I've done my homework and saw that this usually happens when their is an encoding conflict(even though ASCII is a subset of UTF-8...).
So I made sure that when creating the file I'm using using mb_convert_encoding($x, 'UTF-8', 'auto');
to ensure that the JSON is properly being encoded as UTF-8.
I was also using mb_convert_encoding when retrieving the JSON, but saw that double encoding can cause issues so when I removed that piece it no longer echoed out what the encoding was(using mb_detect_encoding) but it is still NULL.
I even went so far as to pull down the JSON file, save it as UTF-8 and re-upload it.
Any and all help on this is much appreciated it. I've banged my head for two days over this. This is built in Code Ignitor, if that makes a difference
Here is the code to create the JSON file:
$thisClient = $this->input->cookie('client');
$date = "%m-%Y";
$date = mdate($date);
$clientDir = *********PATH TO CREATE THE DIRECTORIES IN;
$dialogDir = $clientDir."/".$date;
$d_file_name = $thisClient.'-'.$date;
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($clientDir)){
mkdir($clientDir, 0755, TRUE);
echo "Client Directory Created!<br>";
} else{
echo "No Client Directory Created!<br>";
}
//check to see if client directory exists, if it doesn't then it creates it
if(!is_dir($dialogDir)){
mkdir($dialogDir, 0755, TRUE);
echo "DIALOG Directory Created!<br>";
} else{
echo "No DIALOG Directory Created!<br>";
}
$custDialog = array();
if(isset($_POST['cust-dialog-title'])){
function encodeMe($x){
//this ensure proper encoding
return mb_convert_encoding($x, 'UTF-8', 'auto');
}
$customDialog = array();
for($i = 0; $i < count($_POST['cust-dialog-title']); $i++){
$customDialog[$i]["title"] = encodeMe($_POST['cust-dialog-title'][$i]);
$customDialog[$i]["intro"] = encodeMe($_POST['cust-dialog-intro'][$i]);
for($ii = 0; $ii < count($_POST['cust-dialog-quest-'.$i]); $ii++){
$customDialog[$i]["questions"]["q".$ii] = encodeMe($_POST['cust-dialog-quest-'.$i][$ii]);
if($_POST["cust-dialog-pos-".$i."-".$ii] == "TRUE"){
//if the question is a true positive
$customDialog[$i]["questions"]["agree"] = -5;
$customDialog[$i]["questions"]["disagree"] = 5;
} else{
//if the question is a false positive
$customDialog[$i]["questions"]["agree"] = 5;
$customDialog[$i]["questions"]["disagree"] = -5;
}
}
$jsonDIALOG = json_encode($customDialog);
$jsonDIALOG = str_replace("[", " ", str_replace("]", " ", $jsonDIALOG));
if ( ! write_file($dialogDir."/".$d_file_name.".json", $jsonDIALOG )) {
echo 'Unable to write the file';
} else {
echo 'File written!';
}
//save Custom DIALOG info in database
***********DATABASE INFO**************
}
}
Here is the code to retrieve the JSON object:
if($row["custom"] !== null){ //If the Dialog is a Custom Dialog
$path = str_replace(*****removes an unnecessary portion from the path string**);
$thisDialog = file_get_contents(****PATH TO JSON FILES*****);
//THE FOLLOWING helps debug issues with the JSON -- displays order number and dialog being called -- uncomment to use
//echo $i.' is '.$curDialog[$i]. '<br>';
//$thisDialog = substr($thisDialog,1);
//echo $thisDialog;
//THIS IS THE CODE FOR DEBUGGING ENCODING ISSUES
//$thisDialog = mb_convert_encoding($thisDialog, 'UTF-8', 'ASCII');
//echo mb_detect_encoding($thisDialog);
$jsonDialog = json_decode($thisDialog, true);
echo var_dump($jsonDialog);
if($jsonDialog){
$allDialogs = $jsonDialog;
} else {
echo "Error: Invalid Dialog. Call Order# 0<br>" ;
}
return $allDialogs;
}
I've included some debugging things that I've tried and commented out. Thanks!!
You should probably add JSON_UNESCAPED_UNICODE as an option to json_encode. Keep in mind that this constant is available since PHP 5.4.0
I built a very basic webAPI that when called prints some json data on the screen.
I'm calling the api with the following
function getEnvironmentList(){
$fullUrl = "localhost/serverList/api/rest.php?action=allenvironments&format=json";
$jsonDataRaw = file_get_contents($fullUrl);
return $jsonDataRaw;
}
$jsonData = getEnvironmentList();
echo "<PRE>";
var_dump(json_decode($jsonData, true));
echo "</PRE>";
I get the error Warning: file_get_contents(localhost/serverList/api/rest.php?action=allenvironments&format=json): failed to open stream: No error in C:\path\inc\getJSONdata.php on line 6
Yet when I visit that URL I see this
{"1":{"environmentID":"1","envName":"UAT","envCreatedBy":"mhopkins","envCreatedDtTm":"2013-06-30 00:34:57","envUpdatedBy":"mhopkins","envUpdatedDtTm":"2013-06-30 00:34:57"},"3":{"environmentID":"3","envName":"Platinum","envCreatedBy":"mhopkins","envCreatedDtTm":"2013-06-30 00:37:38","envUpdatedBy":"phpsense","envUpdatedDtTm":"2013-06-30 00:37:38"}}
I'm really confused why the code can't seem to realize there is json data there...
You forgot the http.
$fullUrl = "http://localhost/serverList/api/rest.php?action=allenvironments&format=json";
I'm trying to pull data into flash using JSON but i keep getting this error
JSONParseError: Unexpected < encountered
at com.adobe.serialization.json::JSONTokenizer/parseError()
at com.adobe.serialization.json::JSONTokenizer/getNextToken()
at com.adobe.serialization.json::JSONDecoder/nextToken()
at com.adobe.serialization.json::JSONDecoder()
at com.adobe.serialization.json::JSON$/decode()
at jsonairtest_fla::MainTimeline/decodeJSON()
at flash.events::EventDispatcher/dispatchEventFunction()
at flash.events::EventDispatcher/dispatchEvent()
at flash.net::URLLoader/onComplete()
even though i can runt the pp file in the browser and the ouput looks fine to me, i even tried calling up a txt file and that worked but i don't know what am i doing wrong here.
Here is AS3 code
import com.adobe.serialization.json.JSON
var loader:URLLoader = new URLLoader();
var request:URLRequest = new URLRequest();
request.url = "pull.php";
loader.load(request);
loader.addEventListener(Event.COMPLETE, decodeJSON);
function decodeJSON(event:Event):void{
var loader2:URLLoader = URLLoader(event.target);
//trace(event.target.data);
var People:Array = JSON.decode(loader2.data);
trace(People[0].NETWORKNAME) ;
trace(People[1].NETWORKNAME) ;
}
PHP code:
<?php
$host="localhost";
$user="";
$password="";
$database="db name";
$tablename="table name";
header('Content-type: application/json');
if(!$connection = mysql_connect($host,$user,$password))
{
//if connection not eastablished then display message and die
$message = mysql_error();
//echo "$message<br>";
die();
}else
// in case the connection is eastablished
$message = "Connection eastablished.....";
//echo"$message<br>";
mysql_select_db($database,$connection)
or die("database not found");
$query = mysql_query("SELECT NETWORKNAME from $tablename);
$returnArray = array();
while($row=mysql_fetch_assoc($query))
array_push($returnArray, $row);
mysql_close();
echo json_encode($returnArray);
?>
To convert the response into an array of undecoded JSON objects, try this:
var jsonArray:Array = loader2.data.match(/\{.*?\}/gi);
Then simply loop through calling JSON.decode on each member of the array. :)
In your php output, are you setting your header type to json?
header('Content-type: application/json');
Your decoder may need the type to be correct.
The error message says there's a < in an unexpected position.
My guess is that you are inadvertedly reading your php from the file system, instead of running it on a server. Your file is being not executed as php code and that < is probably the opening tag of your php script (<? or <?php).
If you are running this code from the IDE, your url should be something like:
htp://localhost/my_project/pull.php
If you run this on a browser, you don't need an absolute path, but make sure your swf runs on an http environment (which is able to execute php, of course). That is, test it like this:
http://localhost/my_project/index.php
(where index.php is the hmtl file that embeds your swf)