I am pulling in a list of cities from sba.gov's API. Using SimpleXML I have the following bit of code:
$city_url = 'http://api.sba.gov/geodata/city_links_for_state_of/ca.xml';
$city_xml = simplexml_load_file($city_url) or die("feed not loading");
$city_array = array();
foreach($city_xml as $city) {
$city_array[] = $city->name;
}
//sort($city_array);
//usort($city_array, function($a, $b){ return strcmp($a["name"], $b["name"]); });
print_r($city_array);
The XML format looks like this:
<sites count="431">
<site>
<county_name>Monterey</county_name>
<description nil="true"/>
<feat_class>Populated Place</feat_class>
<feature_id>1536</feature_id>
<fips_class>C1</fips_class>
<fips_county_cd>53</fips_county_cd>
<full_county_name>Monterey County</full_county_name>
<link_title nil="true"/>
<url>http://www.ci.marina.ca.us/</url>
<name>Marina</name>
<primary_latitude>36.68</primary_latitude>
<primary_longitude>-121.8</primary_longitude>
<state_abbreviation>CA</state_abbreviation>
<state_name>California</state_name>
</site>
<site>
<county_name>Contra Costa</county_name>
<description nil="true"/>
<feat_class>Populated Place</feat_class>
<feature_id>1537</feature_id>
<fips_class>C1</fips_class>
<fips_county_cd>13</fips_county_cd>
<full_county_name>Contra Costa County</full_county_name>
<link_title nil="true"/>
<url>http://www.cityofmartinez.org/</url>
<name>Martinez</name>
<primary_latitude>38.01</primary_latitude>
<primary_longitude>-122.13</primary_longitude>
<state_abbreviation>CA</state_abbreviation>
<state_name>California</state_name>
</site>
</sites>
I am trying to create an array from the XML and then sort the array by the name element so that I can output a form drop-down in alpha order.
Thank you for you time!
the problem is that you're building and array of SimpleXMLElement Object
instead of sortable strings. To solve your problem simply cast them when adding elements to the array:
$city_array[] = (string) $city->name;