Jump to content

simplexml_file_load - child may not exist


quasiman

Recommended Posts

I'm writing a dropdown menu of countries states/regions, that pulls from an xml file... but some countries don't have a specific state/region (IE Antarctica).  If they don't, then the XML file isn't formatted in the same way

There is more to this, but the relevant part is here:

echo "<select name=\"statename\">\n";
echo "<option value=\"\">Select a state</option>\n";
$statexml = simplexml_load_file($state);
		foreach ($statexml->geoname as $statelink)  {
			if($statelink) {
echo "<option value='{$statelink->name}'>{$statelink->name}</option>\n";
} else {
	echo "<option value='none'>none</option>\n";
		}
	}
echo "</select>";

 

A state xml with results looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<geonames style="MEDIUM">
<totalResultsCount>51</totalResultsCount>
<geoname>
<name>Alabama</name>
...etc, etc
</geoname>
<geoname>
<name>Alaska</name>
...etc, etc
</geoname>
</geonames>

 

And an xml with no results looks like this:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<geonames>
<status message="no children for Antarctica 6697173" value="15"/>
</geonames>

 

Saying the if($statelink) isn't working, as any country without a state simply doesn't display the 'none' selection.

<select name="statename">
<option value="">Select a state</option>
</select>

 

 

Any help??  :(

Link to comment
https://forums.phpfreaks.com/topic/227831-simplexml_file_load-child-may-not-exist/
Share on other sites

Tried that, (below) with the same results

$statexml = simplexml_load_file($state);
		foreach ($statexml->geoname as $statelink)  {
			if(isset($statelink->name)) {
echo "<option value='{$statelink->name}'>{$statelink->name}</option>\n";
} else {
	echo "<option value='none'>none</option>\n";
		}
	}
echo "</select>";

It seems like this board gets too much traffic to have anything answered without bumping it....anyway, I got it fixed:

 

	$statexml = simplexml_load_file($state);
if (count($statexml->geoname)) {
echo "<select name=\"statename\">\n";
echo "<option value=\"\">Select a state</option>\n";
		foreach ($statexml->geoname as $statelink)  {
				echo "<option value=$statelink->name>$statelink->name</option>\n";
		}
} else {
	echo "<input type=\"text\" name=\"statename\" value=\"\"\n";
}
echo "</select>";

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.