I'm trying to get data from:
http://natomilcorp.com/api/get-users
But when I try it nothing is working.
$url = "http://natomilcorp.com/api/get-users";
$jsonString = file_get_contents($url);
$obj = json_decode($jsonString);
echo $obj->"username";
I try JQuery but I was not able to make it work.
I will like to get the username, lastseen and datejoined.
If someone could help me with this.
The things that could have gone wrong are:
The website is not responding
The JSON is invalid
There is some error in your code
This code should tell your what is happening:
error_reporting(-1); // Turn on error reporting
$url = "http://natomilcorp.com/api/get-users";
$jsonString = file_get_contents($url);
if ( ! $jsonString) {
die('Could not get data from: '.$url);
}
$obj = json_decode($jsonString);
if ( ! $obj) {
// See the following URL to figure out what the error is
// Be sure to look at the comments, as there is a compatibility
// function there
// http://php.net/manual/en/function.json-last-error-msg.php
die('Something is wrong with the JSON');
}
echo $obj->"username";
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
}
I'm using Factory in AngularJS, The Script is
app.factory('GetCountryService', function ($http, $q) {
return {
getCountry: function(str) {
// the $http API is based on the deferred/promise APIs exposed by the $q service
// so it returns a promise for us by default
var url = "https://www.bbminfo.com/sample.php?token="+str;
return $http.get(url)
.then(function(response) {
if (typeof response.data.records === 'object') {
return response.data.records;
} else {
// invalid response
return $q.reject(response.data.records);
}
}, function(response) {
// something went wrong
return $q.reject(response.data.records);
});
}
};
});
My Output Response Screen Shot:
My PHP Script:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
session_start();
$ip = $_SERVER['REMOTE_ADDR'];
$dbname = "xyzData";
$link = mysql_connect("localhost", "Super", "Super") or die("Couldn't make connection.");
$db = mysql_select_db($dbname, $link) or die("Couldn't select database");
$uid = "";
$txt = 0;
$outp = "";
$data = file_get_contents("php://input");
$objData = json_decode($data);
if (isset($objData->token))
$uid = mysql_real_escape_string($objData[0]->token, $link);
else if(isset($_GET['uid']))
$uid = mysql_real_escape_string($_GET['uid']);
else
$txt += 1;
$outp ='{"records":[{"ID":"' . $objData->token . '"}]}';
echo($outp);
?>
I got error_log message is
[18-Mar-2016 21:40:40 America/Denver] PHP Notice: Trying to get
property of non-object in /home/sample.php
I tried both $objData->token and $objData->token[0]. But I got the same error notice. Kindly assist me...
I tried the Solution provided in the Post Notice: Trying to get property of non-object error, But it fails so, I raised 50 Bounty Points for this post. I tried to update my requirement in that post Question https://stackoverflow.com/review/suggested-edits/11690848, But the Edit was Rejected so I posted my requirement as a new Question. Kindly assist me...
The AngularJS is not sending any Object instead it passes the GET element.
Just access the Value by simply using $_GET['uid']
$objData doesn't seem to be an object.
try $objData['token'].
Or echo the object $objData and try to figure out what is its structure.
I've been using this over 2 months and worked fine until some days ago, when an error message appeared.
I use the steam api to get some info of the players.
$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
The page is not blank, it has an xml document. So my first thinking was that my host had turned allow_url_fopen off, but they don't (I asked them).
I also tried using error_reporting(E_ALL); ini_set('display_errors', 1);
And that's what I get:
Warning: simplexml_load_file() [function.simplexml-load-file]: I/O warning : failed to load external entity "" on line 6
Notice: Trying to get property of non-object on line 7
Now I'm using this: $xml = simplexml_load_file(file_get_contents($url));
And I would love to continue using it because installing cURL it's not an option right now. Do you know of a better (or a working) way to get this done? Or how to fix this error?
My full code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
//$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
$url = "xml.txt";
ini_set('allow_url_fopen ','ON');
$xml = file_get_contents($url) or die ("file_get_contents failed");
$xml = simplexml_load_string($xml) or die ("simplexml_load_string failed");
$profilepic = $xml->avatarIcon;
$pic = $xml->avatarFull;
$steamID = $xml->steamID;
$lastonline = $xml->stateMessage;
echo $xml;
echo $profilepic;
echo $pic;
echo $steamID;
echo $lastonline;
EDIT:
If I use the internal url it loads the data, but when I try to use any url that uses http protocol just launches the file_get_contents failed error, even if the url is my website's one. I'm willing to use cURL if there's no other solution. I also thought about making a php script that loads the data and saves it in a file in the server (and then run a cronjob every 10 min), but it would use the file_get_contents anyway...
file_get_content returns a string so use simplexml_load_string instead.
This code works for me, tested.
$url = "http://steamcommunity.com/id/CGaKeepoN/?xml=1";
$xml = simplexml_load_string(file_get_contents($url));
$profilepic = $xml->avatarIcon;
$pic = $xml->avatarFull;
$steamID = $xml->steamID;
$lastonline = $xml->stateMessage;
var_dump($url);
var_dump($xml); //-> string(45) "http://steamcommunity.com/id/CGaKeepoN/?xml=1" bool(false)
echo $xml;
echo $profilepic;
echo $pic;
echo $steamID;
echo $lastonline;
I have a JSON file that looks a little like this:
[
{
"uniqid":"sd54sd54f",
"Make":"Toyota",
"Start Prod":258147369,
"End Prod":369147258
},
{
"uniqid":"6sdf46sd",
"Make":"BMW",
"Start Prod":789456123,
"End Prod":159487263
},
]
What I need to do is remove an entire entry (uniqid, make, start prod and end prod) based on a uniqid that will be passed in through an HTTP POST request. So far all I have is:
$var1 = $_GET['uniqid'];
$file = 'cars.json';
$json = json_decode(file_get_contents($file), true); //im not sure if file_get_contnets is necessary...
$unset_queue = array();
foreach ( $json as $i => $item )
{
if ($item->uniquid == $var1)
{
$unset_queue[] = $i;
}
}
foreach ( $unset_queue as $index )
{
unset($json->json[$index]);
}
$json = array_values($json);
$new_json_string = json_encode($json);
When I run the code, I get no errors but the item is not removed...
EDIT: Here is the output issue at this point. Note the numbering of each car:
{"1":
{
"uniqid":"sd54sd54f",
"make":"Toyota",
"start prod":"258147369",
"end prod":"369147258"
},
"2":
{
"uniqid":"5372ab2109b05",
"make":"6sdf46sd",
"start prod":"789456123",
"end prod":"159487263"},
}
}
You have mentioned that you will be passing your request through HTTP POST. In that case , in order to make your code to work, you should change $var1 = $_GET['uniqid']; to $var1 = $_POST['uniqid'];
You can use a simple function with the JSON variable passed by reference:
function removeNode($uniqid, &$json) {
$json = json_decode($json, true); // get associative array from json
foreach($json as $key => $each) { // loop through
if($each['uniqid'] == $uniqid) // find matching unique
unset($json[$key]); // remove node from array
}
$json = json_encode($json); // re-encode array as json
}
And use like this:
removeNode('6sdf46sd', $json);
Example: https://eval.in/150341
Specific use case for you:
$var1 = $_POST['uniqid']; // you're posting the data right?
$file = 'cars.json';
$json = file_get_contents($file);
removeNode($var1, $json);
echo $json; // updated JSON
// or if you want to update the file:
// file_put_contents($file, $json);
Well, there are a couple of things wrong:
You are not checking that your code does what you think it does. It is important to check for errors.
You can unset the item inside the first loop. The second loop is not necessary.
Inside the second loop you are accessing an object and property that does not exist. When you decoded the JSON you specifically told it to return arrays.
First of all you should put this at the top of your script:
error_reporting(-1);
ini_set('display_errors', 'On');
That will show you every single error that occurs.
Second, you should fix your code. I just rewrote and commented your code. It is easier to show you than explain.
// Make sure that you are notified of all errors
error_reporting(-1);
ini_set('display_errors', 'On');
// Get 'uniqid' from POST/GET array; show error if
// it is not set
$var1 = filter_input(INPUT_POST, 'uniqid', FILTER_UNSAFE_RAW);
if ($var1 === null) {
die('The "uniqid" parameter is not set');
}
// Read data from file; show error if it does not work
$data = file_get_contents('cars.json');
if ($data === false) {
die('An error occurred when opening "cars.json"');
}
// Decode JSON; show error if invalid JSON
$json = json_decode($data, true);
if ( ! isset($json[0]['uniqid'])) {
die("The JSON was not decoded correctly");
}
// Go over each item in the array
foreach ($json as $key => $value) {
// If the 'uniqid' equals GET parameter
if ($value['uniqid'] == $var1) {
// Then unset it using the item's $key position
unset($json[$key]);
}
}
// Encode it again
$new_json_string = json_encode($json);
If it is a GET request then you can use this instead:
// ...
$var1 = filter_input(INPUT_GET, 'uniqid', FILTER_UNSAFE_RAW);
// ...
When you are done with the code, and you make it live, you should disable errors:
ini_set('display_errors', 'Off');
That makes sure that people cannot see the errors. Error messages often include file names and such, which is not something people should see.
$inputDatabase = array_values(json);
I can retrieve certain information with a rest command, the data it shows (in the browser) is already an XML. How do I save it to an XML file on the server after retrieving the information.
I have already tried it with the $dom-save command but I seem to do something wrong. Any help would be appreciated. See below for code (I want to save the $response to XML.)
<?php
require_once 'includes/rest_connector.php';
require_once 'includes/session.php';
// check to see if we start a new session or maintain the current one
checksession();
$rest = new RESTConnector();
$url = "/api/tax_codes/0/";
$rest->createRequest($url,"GET", null, $_SESSION['cookies'][0]);
$rest->sendRequest();
$response = $rest->getResponse();
$error = $rest->getException();
// save our session cookies
if ($_SESSION['cookies']==null)
$_SESSION['cookies'] = $rest->getCookies();
// display any error message
if ($error!=null)
echo $error;
// display the response
if ($response!=null)
echo $response;
else
echo "There was no response.";
?>
The RESTConneconnector is a specific class Lightspeed. I solved it by using this:
ibxml_use_internal_errors(true);//load if improperly formatted
file_put_contents("exportProduct.xml", $responseProduct);
So it was very easy in the end :)
I dont know any about RESTConnector class. But I suppose, you can try something like it:
$dom = new DOMDocument('1.0','utf-8');
$dom->preserveWhiteSpace = false;
$dom->formatOutput = true;
$dom->loadXML($response->asXML());
$dom->save($this->fileexport);