How to loop through a JSON array and put data in variables - php

I am trying to get the data from an API and save it to a MySQL database. The problem is when I want to echo the data to check if it gets all the values I'm getting this error:
Notice: Trying to get property of non-object
My JSON data looks like this:
{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"},
I think this is because it is in an array. Because when I use this bit of code it gives no errors but I have to define the index of the array. What is the best way to loop through my data and put it in variables?
<?php
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = $data->AttractionInfo[0]->Id;
$attractieType = $data->AttractionInfo[0]->Type;
$attractieStatus = $data->AttractionInfo[0]->State;
$attractieStatusKleur = $data->AttractionInfo[0]->StateColor;
$attractieWachttijd = $data->AttractionInfo[0]->WaitingTime;
$attractieStatusPercentage = $data->AttractionInfo[0]->StatePercentage;
?>
I tried to find some solutions but all they use is a foreach loop. But i don't think that'll work right. Can anyone help me in the good direction or tell me how I might possibly fix this? I am not very experienced so any advice is welcome. Thanks in advance.
Update code:
require 'database-connection.php';
//Get content
$url = "https://eftelingapi.herokuapp.com/attractions";
$data = json_decode(file_get_contents($url));
//Fetch data
$attractieId = isset($data->AttractionInfo->Id);
$attractieType = isset($data->AttractionInfo->Type);
$attractieStatus = isset($data->AttractionInfo->State);
$attractieStatusKleur = isset($data->AttractionInfo->StateColor);
$attractieWachttijd = isset($data->AttractionInfo->WaitingTime);
$attractieStatusPercentage = isset($data->AttractionInfo->StatePercentage);
$sql = "INSERT INTO attracties (attractieId, attractieType, attractieStatus, attractieStatusKleur, attractieWachttijd, attractieStatusPercentage)
VALUES ('$attractieId', '$attractieType', '$attractieStatus', '$attractieStatusKleur', '$attractieWachttijd', '$attractieStatusPercentage')";
if ($db->query($sql) === TRUE) {
echo "success";
} else {
echo "Error: " . $sql . "<br>" . $db->error;
}
It says 'success' but when I look into my database it inserted only empty data. I need to add all the attractions to my database so not just one row. So I need to loop through my data.

try this...
$content = json_decode(file_get_contents($url));
foreach($content->AttractionInfo as $data ){
$id = $data->Id;
$type = $data->Type;
$map = $data->MapLocation;
$state = $data->State;
$color = $data->StateColor;
if(!empty($data->WaitingTime)) {
$time = $data->WaitingTime;
}
if(!empty($data->StatePercentage)) {
$percent = $data->StatePercentage;
}
//persist your data into DB....
}

I think you need something like this:
$json = '{"AttractionInfo":[{"Id":"sprookjesbos","Type":"Attraction","MapLocation":"1","State":"open","StateColor":"green","WaitingTime":0,"StatePercentage":0},{"Id":"zanggelukkig","Type":"Show","MapLocation":".","State":"gesloten","StateColor":"clear"}]}';
$arr = json_decode($json);
foreach ($arr->AttractionInfo as $key => $attraction) {
foreach($attraction as $key=> $value) {
print_r($key.' - '.$value.'<br>');
$$key = $value;
}
}
echo '<br>';
echo $Id; // it will be last item/attraction id.
We can improve this code. Just say where and how do you want to use it

Related

PHP Array & XML Can't get all content

I'm tring to get all content from this xml: https://api.eveonline.com/eve/SkillTree.xml.aspx
To save it on a MySQL DB.
But there are some data missing...
Could any1 that understand PHP, Array() and XML help me, please?
This is my code to get the content:
<?php
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
for ($x=0;$x<sizeOf($xmlbalance->result->rowset->row);$x++) {
$groupName = $xmlbalance->result->rowset->row[$x]->attributes()->groupName;
$groupID = $xmlbalance->result->rowset->row[$x]->attributes()->groupID;
for ($y=0;$y<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row);$y++) {
$skills[$x]["skillID"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeID;
$skills[$x]["skillName"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->attributes()->typeName;
$skills[$x]["skillDesc"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->description;
$skills[$x]["skillRank"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rank;
$skills[$x]["skillPrimaryAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->primaryAttribute;
$skills[$x]["skillSecondAtr"] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->requiredAttributes->secondaryAttribute;
$o = 0;
for ($z=0;$z<sizeOf($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row);$z++) {
if ($xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->attributes()->name == "requiredSkills") {
$skills[$x]["requiredSkills"]["".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->typeID] = "".$xmlbalance->result->rowset->row[$x]->rowset->row[$y]->rowset->row[$z]->attributes()->skillLevel;
$o++;
}
}
}
}
echo '<pre>'; print_r($skills); echo '</pre>';
?>
If you go to the original XML (link), at line 452, you will see:
<row groupName="Spaceship Command" groupID="257">
And that isn't show in my array (link)...
That is one thing that i found that is missing...
I think that probally have more content that is missing too..
Why? How to fix it, please?
Thank you!!!
You will only get a total of sizeof($xmlbalance->result->rowset->row) records. Because, in your 2nd for loop, you are basically storing your result in the same array element that is $skills[$x].
Try this (I also higly encourage you to be as lazy as you can when you write code - by lazy I mean, avoid repeating / rewriting the same code over and over if possible) :
$filename = 'https://api.eveonline.com/eve/SkillTree.xml.aspx';
$xmlbalance = simplexml_load_file($filename);
$skills = array();
foreach ($xmlbalance->result->rowset->row as $row)
{
$groupName = $row->attributes()->groupName;
$groupID = $row->attributes()->groupID;
foreach ($row->rowset->row as $subRow)
{
$skill['skillID'] = (string) $subRow->attributes()->typeID;
$skill['skillName'] = (string) $subRow->attributes()->typeName;
$skill['skillDesc'] = (string) $subRow->description;
$skill['skillRank'] = (string) $subRow->rank;
$skill['skillPrimaryAtr'] = (string) $subRow->requiredAttributes->primaryAttribute;
$skill['skillSecondAtr'] = (string) $subRow->requiredAttributes->secondaryAttribute;
foreach ($subRow->rowset as $subSubRowset)
{
if ($subSubRowset->attributes()->name == 'requiredSkills')
{
foreach ($subSubRowset->row as $requiredSkill)
{
$skill['requiredSkills'][(string) $requiredSkill->attributes()->typeID] = (string) $requiredSkill['skillLevel'];
}
}
}
$skills[] = $skill;
}
}
print_r($skills);

PHP array : Echo a $var inside a form with option value [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
How can I display variable $player->name inside a form option value so user could select variable and submit form.
Here's my code that is not working :
<?php
$team = $_POST['team'];
$result = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/$team/iphone/clubroster.j son");
$json = json_decode($result);
$goalies = $json->goali;
foreach ($json->goalie as $player) {
**echo "<option value=\"".$player->name."\">".$player->name."</option>**
}
?>
You did not have the double quotes and semicolon at the end of statement.
<?php
$team = $_POST['team'];
$result = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/$team/iphone/clubroster.json");
$json = json_decode($result);
$goalies = $json->goali;
foreach ($json->goalie as $player) {
echo "<option value=\"".$player->name."\">".$player->name."</option>";
}
?>
What is this $json->goalie value in foreach , use $goalies instead
<?php
$team = $_POST['team'];
$result = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/$team/iphone/clubroster.json");
$json = json_decode($result);
$goalies = $json->goali;
foreach ($goalies as $player)
{
echo "<option value='".$player->name."'>".$player->name."</option>";
}
?>
Besides the obvious parse error you have in your code, here are some other things to look out for:
$team = $_POST['team'];
$result = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/$team/iphone/clubroster.json");
You can't just use $team inside a URL like that, you're supposed to encode it:
$url = sprintf("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/%s/iphone/clubroster.json",
urlencode($team)
);
$result = file_get_contents($url);
$json = json_decode($result);
foreach ($json->goalie as $player) {
echo "<option value=\"".$player->name."\">".$player->name."</option>";
}
You should always escape your variables in output:
printf('<option value="%s">%1$s</option>',
htmlspecialchars($player->name, ENT_QUOTES, 'UTF-8')
);
I'd recommend decoding your JSON to an array, not an object, it is easier to work with.
You aren't using the goalies variable in your above code, I'm assuming that's what you want to use in the foreach statement?
Error checking would be a good idea
If so, then your code may look something like this:
<?php
$team = $_POST['team'];
$result = file_get_contents("http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/$team/iphone/clubroster.json");
$json = json_decode($result, true);
$goalies = array();
if (!empty($json['goali'])) {
$goalies = $json['goali'];
}
foreach ($goalies as $player) {
echo '<option value="' . $player['name'] . '">' . $player['name'] . '</option>'
}
?>
If you want to display varibles inside string then always use "" for displaying the variable. You can modify your code as:
echo "<option value='{$player->name}'>{$player->name}</option>";
So always remember:
1. You can use ''(singlequots) inside ""(doublequotes)
You were not using the ' correctly around your variables.
Demo
<?php
// Create a dummy Object
$player = new stdClass();
// Create a dummy property
$player->name = "Occam's Razor";
// Print it out
echo '<option value=" '.htmlspecialchars($player->name).' ">' .htmlspecialchars($player->name). '</option>';
This prints out the following.
<option value=" Occam's Razor ">Occam's Razor</option>
Instead of writing about what the problem is, I think it would be more helpful to just show you, and give you some pointers:
// Make sure all errors are displayed
error_reporting(E_ALL);
ini_set('display_errors', 1);
// Get the team variable and make sure that it was set
$team = filter_input(INPUT_POST, 'team', FILTER_UNSAFE_RAW);
if ($team === null) {
die('Error: The "team" POST variable is not set, cannot continue');
}
// Since you are using the variable inside a URL it makes
// sense to remove potentially unsafe characters; or in
// other words, only preserve characters that are allowed.
// Encoding the variable, as in Ja͢ck's answer, is also an option.
$team = preg_replace('/[^a-zA-Z0-9_-]/', null, $team);
if ($team === "") {
die('Error: The "team" variable is empty, cannot continue');
}
// Construct the URL
$url = "http://nhlwc.cdnak.neulion.com/fs1/nhl/league/teamroster/{$team}/iphone/clubroster.json";
// Grab the data from the website
$data = file_get_contents($url);
if ($data === false) {
die('Error: Could not grab the data from the URL, cannot continue');
}
// Attempt to decode the data
$json = json_decode($data);
if (json_last_error() !== JSON_ERROR_NONE) {
die('Error: There was a JSON error ('.json_last_error_msg().'), cannot continue');
}
// Since we are expecting an object we should check for it
// before using it
if ( ! is_object($json)) {
die('Error: The JSON was decoded, but is not an object, cannot use it...');
}
// If the following code gives you problems then read the error
// message, try to understand what it says, and then google it if
// you are getting nowhere
$goalies = $json->goali;
foreach ($json->goalie as $player) {
echo "<option value=\"".$player->name."\">".$player->name."</option>";
}

Retrieve all values in my loop and format it to json

I'm trying to build a page which queries my database and then formats output so another webservice/page can access the data.
Ideally I wanted to explore having the data in JSON format, but that is not working. The other problem I have which is more major than the JSON not working is, if I have 3 records in $reportsResult, only the last one is displayed.
Anyone with some help please. Oh do I also need to print_r for the external webpage to retrieve the data or is there a better way?
class Pupil {
public $FirstName = "";
public $LastName = "";
}
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
}
json_encode($Pupil);
OK managed to figure out how how to get all records from the loop, but its still not displaying in json format when I do a print_r - am I missing something?
$AllPupils = array();
foreach($reportsResult->getRecords() as $reportRecord)
{
$Pupil = new Pupil();
$Pupil->FamID = $reportRecord->getField('FName');
$Pupil->ChildName = $reportRecord->getField('SName');
array_push($AllPupils, $Pupil);
}
json_encode($AllPupils);
Everytime your foreach loop starts again, it will override your $Pupil variable.
Try an array instead:
$Pupil = array()
$i = 0;
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil[$i] = new Pupil();
$Pupil[$i]->FirstName = $reportRecord->getField('FName');
$Pupil[$i]->LastName = $reportRecord->getField('SName');
$i++;
}
echo json_encode($Pupil);
Edit: mikemackintosh's solution should also work and could be a little bit faster (depending on the size of your foreach loop).
To display the results you need to echo your data (not only json_encode).
You will probably run into issues since json_encode wont handle the whole object. for that, you may want to serialize the $Pupil object.
Something like below may work for you though. It will assign the values to a returned array, which will allow json_encode to execute gracefully:
class Pupil {
public $FirstName = "";
public $LastName = "";
public function getAttr(){
return array("FirstName" => $this->FirstName, "LastName" => $this->LastName);
}
}
$json = array();
foreach($reportsResult->getRecords() as $reportRecord) {
$Pupil = new Pupil();
$Pupil->FirstName = $reportRecord->getField('FName');
$Pupil->LastName = $reportRecord->getField('SName');
$json[] = $Pupil->getAttr();
}
echo json_encode($json);
I am not sure why you have that class defined, but you know what in your for each have something like
foreach ($reportsResult->getRecords() as $key => $record) {
$data[$key]['firstname'] = $record->getField('Fname');
$data[$key]['lastname'] = $record->getField('Sname');
}
And then you can check the final array using print_r
and while output you can simply do a print json_encode($data) and it will give you a json string of all the items in the data array.
In php (at least), json_encode takes an array as parameter.
Therefore you should add a constructor to your class
function __construct($first, $last)
{
this.$FirstName = $first;
this.$LastName = $last;
}
and one for getting the full name as an array, ready to be jsoned
function getNameArray()
{
$nameArray = array();
$nameArray['firstName'] = this.$FirstName;
$nameArray['lastName'] = this.$LastName;
return $nameArray;
}
then in that foreach you build another array with all the pupils
$pupils = array();
foreach (bla bla)
{
$first = $reportRecord->getField('FName');
$last = $reportRecord->getField('SName');
$Pupil = new Pupil($first, $last);
array_push($pupils, $pupil.getNameArray());
}
finally, you have everything preped up
json_encode($pupils);
I'm sure there's other ways to debug your stuff, I use print_r mainly also.

building an associative array

This is going to be my first time building an associative array. And if anyone can help me I would be grateful.
Basically, I want to loop through a directory of XML files. I want to find out if a certain editor was the editor of this file, and if the query is true, I would like to grab two pieces of information and achieve the result of an associate array with those two pieces of information for every case where the editor's name is found.
So here's what I have got so far:
function getTitleandID($editorName) {
$listofTitlesandIDs = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
if ($editorName == $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()"))
{
$title = $xmldoc->xpath("//tei:teiHeader/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id[1]");
$listofTitlesandIDs[] = //I don't know what to do here
}
else
{
$listofTitlesandIDs = null;
}
}
return $listofTitlesandIDs
}
This is about where I get stuck. I'd like to be able have $listofTitlesandIDs as an associative array where I could call up the values for two different keys, e.g. $listofTitlesandIDs['title'] and $listofTitlesandIDs[$id]
So that's about it. I'm grateful for any help you have time to provide.
Well I'm sure this is a little clumsy (the result of an amateur) but it has given me the result I want.
function getTitlesandIDs($EditorName) //gets titles and IDs for given author
{
$list = array();
$filename = readDirectory('../editedtranscriptions');
foreach($filename as $file)
{
$xmldoc = simplexml_load_file("../editedtranscriptions/$file");
$xmldoc->registerXPathNamespace("tei", "http://www.tei-c.org/ns/1.0");
$title = $xmldoc->xpath("//tei:teiHeader/tei:fileDesc/tei:titleStmt/tei:title[1]");
$id = $xmldoc->xpath("//tei:text/tei:body/tei:div/#xml:id");
$editorName = $xmldoc->xpath("//tei:editor[#role='PeerReviewEditor']/text()")
if ($editorName[0] == "$EditorName")
{
$result = array("title"=>$title[0], "id"=>$id[0]);
$list[] = $result;
}
}
return $list;
}
With this I can call the function $list = getTitlesandIDs('John Doe') and then access both the title and id in the associative array for each instance. Like so:
foreach ($list as $instance)
{
echo $instance['title'];
echo $instance['id'];
}
Maybe that will help somebody some day -- let me know if you have any advice on making this more elegant.
$listofTitlesandIDs[$id] = $title;
You should loop over the array then using the foreach loop.

Inserting all the Gamertags from a game history page.?

I can't figure out how to get all the gamertags from the output, and then insert them into a mysql table.
This is what I have so far, read the comments... Thank you!
<?php
//gameID
$gameid = "469547013";
//key to access api
$apikey = "30cRxVA9J73esG388CzmOXUVRo5VjYhSfI2qBaqcMzs=";
$url = "http://www.bungie.net/api/reach/reachapijson.svc/game/details/".$apikey."/".$gameid."";
$output = file_get_contents($url);
$obj = json_decode($output);
//output
print_r($output);
//json_decoded output
print_r($obj);
//Having a hard time getting a single gamertag
print $obj->GameDetails->Players->PlayerDetail[0]->gamertag;
//I guess there needs to be an array or arrays here
$result = ????????????;
while ($tag = $result) {
//value
$tag = $array['gamertag'];
//insert each gamertag into table
mysql_connect('localhost', '', '') or die('Error connecting to MySQL');
mysql_select_db('');
mysql_query("INSERT IGNORE INTO gamertags(gamertag)VALUES ('".$tag."')");
}
?>
Check this out:
$output = file_get_contents('http://www.bungie.net/api/reach/reachapijson.svc/game/details/30cRxVA9J73esG388CzmOXUVRo5VjYhSfI2qBaqcMzs=/469547013');
$output = json_decode($output);
foreach($output->GameDetails->Players as $player) {
echo $player->PlayerDetail->gamertag . '<br />';
}
edit Take a look at http://dbug.ospinto.com/. I through the decoded json into it and it told me exactly how to get what I needed.
Players is an array, so you'll want something like this:
print $obj->GameDetails->Players[0]->PlayerDetail->gamertag;
So then you'll want to loop through the Players array and get each tag. Something like this:
$ary = new Array();
foreach($obj->GameDetails->Players as $player) {
$ary[] = $player->PlayerDetail->gamertag;
}

Categories