我从sba.gov的API中提取城市列表。使用SimpleXML我有以下代码:
$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);
XML格式如下所示:
<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>
我正在尝试从XML创建一个数组,然后按名称元素对数组进行排序,以便我可以按字母顺序输出表单下拉列表。
谢谢你的时间!
答案 0 :(得分:0)
问题在于您正在构建SimpleXMLElement Object
而不是可排序字符串。要解决您的问题,只需在向数组添加元素时强制转换它们:
$city_array[] = (string) $city->name;