我正在尝试将xml转换为数组,以便我可以将它用于JSON。 与城市搜索的jquery代码一起使用: jquery的
<script type="text/javascript">
$(document).ready(function(){ var ac_config = { source: "cities.php", select: function(event, ui){ $("#City").val(ui.item.City); $("#Country").val(ui.item.Country); $("#DestinationID").val(ui.item.DestinationId); }, minLength:3 };
$("#City" ).autocomplete(ac_config); });
</script>
Xml看起来像:
<CIties>
<Destination>
<DestinationId>1SVV</DestinationId>
<Country>Canada</Country>
<City>100 Mile House</City>
<State>BC</State>
</Destination>
<Destination>
<DestinationId>1X9K</DestinationId>
<Country>Netherlands</Country>
<City>1c3d</City>
<State></State>
</Destination>
<Cities>
数组如下面的模型
$Destinations= array(
array('City'=>'Rome', Country=>'Italy', DestinationId=>'RHMK'),
array('City'=>'Los Angeles', Country=>'CA', DestinationId=>'90001'),
array('City'=>'Chicago', Country=>'IL', DestinationId=>'60601'), );
我试过了:
<?php // Data could be pulled from a DB or other source
$xmlstring = file_get_contents("city.xml");
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
// Cleaning up the term
$term = trim(strip_tags($_GET['term']));
// Rudimentary search
$matches = array(); foreach($cities as $City){ if(stripos($City['City'], $term) !== false){
// Add the necessary "value" and "label" fields and append to result set
$City['value'] = $City['City']; $City['label'] = "{$City['City']}"; $matches[] = $City; } }
// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5); print json_encode($matches);
?>
但是不起作用