一般来说国家列表非常长的,在客户端一般不使用连接数据库来读取数据的国家列表。这不仅消耗内存而且让页面加载速度也变慢,为此把国家列表存在XML中是一个很好的选择。
部分XML数据:data/countries.xml,列表太长,完整的放在附件中。
PHP函数及调用方法:index.php
function get_country_select($xml, $sele=0,$type='id'){
if(!file_exists($xml)) return 'File not exists';
$country_xml = simplexml_load_file($xml);
$list = '';
foreach($country_xml->children() as $region){
$list .= "\n";
foreach($region->children() as $country){
$country_id = $country['id'];
$country_name = $country['name'];
$list.='
if($sele == $country_id) $list.= ' selected';
}else{
$list.= $country_name.'"';
if($sele == $country_name) $list.= ' selected';
}
$list .= '>'.$country_name."
\n";}
$list .= "\n";
}
return $list;
}
$xml = './data/countries.xml';
$list = get_country_select($xml);
echo '';
echo $list;
echo '';
为什么要把写在函数外面呢?因为往往select需要id,name毕竟提交表单需要一些信息,个人并不喜欢函数带太多参数。
国家列表完整XML下载:countries.xml
PHP读取XML国家列表 was published on September 13, 2010