I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "undefined" in each cell. I've checked the code multiple times but can't seem to find the root cause. If anyone has any fresh ideas on how to solve this problem, please let me know!
<html>
<head>
<h1><u>USA State Information</u></h1>
</head>
<body>
<p><b>Please select an area of the USA from the dropdown list below.</b></p>
<p><select name="area" onchange="findXML(this.value)">
<?php
//set directory and open it
$xmldir = 'XML';
$dir = opendir($xmldir);
//create array and read through files in directory
$xmlfiles = array();
while ($file = readdir($dir))
{
//if the first char is not '.' then add to array
if (substr($file,-1,1) !== ".")
{
$xmlfiles[] = $file;
}
else
{
//do nothing
}
}
echo '<option value="select">Select</option>';
foreach($xmlfiles as $area){
echo '<option value="'.$area.'">'.$area.'</option>';
}
echo '</select>';
//close directory
closedir($dir);
?>
</p>
<p>
<div id=tbl>
</div>
<table id="elems" border="1" cellspacing="1" cellpadding="5">
<tr>
<td><b>Name</></td>
<td><b>Number</></td>
<td><b>Joined</></td>
<td><b>Population</></td>
</tr>
</table>
<script>
function findXML($area) {
$area = "XML/" + $area;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",$area,true);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
//find number of elements in the XML file
$length = xmlDoc.getElementsByTagName("name").length;
var JSONObject = [{}];
for (i=0; i!=$length; i++){
//do something
JSONObject.push(
{ "name":(xmlDoc.getElementsByTagName("name")[i].childNodes[0].nodeValue),
"number":(xmlDoc.getElementsByTagName("number")[i].childNodes[0].nodeValue),
"joined":(xmlDoc.getElementsByTagName("joined")[i].childNodes[0].nodeValue),
"population":(xmlDoc.getElementsByTagName("population")[i].childNodes[0].nodeValue) }
);
}
r=1;
i=0;
for (i=0; i!=($length); i++){
var tblr = document.getElementById("elems").insertRow(r);
var cell1= tblr.insertCell(0);
var cell2= tblr.insertCell(1);
var cell3= tblr.insertCell(2);
var cell4= tblr.insertCell(3);
cell1.innerHTML = JSONObject[i].name;
cell2.innerHTML = JSONObject[i].number;
cell3.innerHTML = JSONObject[i].joined;
cell4.innerHTML = JSONObject[i].population;
r++;
}
}
</script>
</p>
</table>
</body>
</html>