XML输出如下
<?xml version="1.0" encoding="UTF-8"?>
<Country code="GR">
<Regions>
<Region translation="null">Athens Airport</Region>
<Region translation="null">Athens Coast</Region>
<Region translation="null">Athens Suburbs-Attica</Region>
<Region translation="null">Athens</Region>
<Region translation="null">Central Greece-Etoloakarnania</Region>
<Region translation="null">Central Greece-Evritania</Region>
<Region translation="null">Central Greece-Ioannina</Region>
<Region translation="null">Central Greece-Karditsa</Region>
<Region translation="null">Central Greece-Larissa</Region>
<Region translation="null">Central Greece-Magnissia</Region>
</Regions>
</Country>
每个地区都有城市,如下
<?xml version="1.0" encoding="UTF-8"?>
<Country code="GR">
<Cities>
<City translation="null">Acharnes</City>
<City translation="null">Achladies</City>
<City translation="null">Achladochori</City>
<City translation="null">Adamas</City>
<City translation="null">Afandou</City>
<City translation="null">Afiartis</City>
<City translation="null">Agali</City>
<City translation="null">Aghia Anna</City>
<City translation="null">Aghia Paraskevi</City>
</Cities>
我需要的是将每个地区和国家/地区下的所有城市都插入到桌子中。 一个国家有许多地区,一个地区有多个城市。 我试过的是
$regions = array("GR" => "Greece", "BR" => "Brazil", "US" => "USA");
foreach ($regions as $code => $country) {
$url = "URL which gives an xml output"
file_put_contents($code . '.xml', file_get_contents($url));
$xml = simplexml_load_file($code".xml") or die("Error: Cannot create object");
foreach ($xml->children() as $row) {
$region = $row->Region;
}
}
如何循环并将其保存在mysql中? TIA
答案 0 :(得分:0)
如果你的.XML输出是这样的:
<?xml version="1.0" encoding="UTF-8"?>
<Country>
<Code></Code>
<Regions>
<Region>
<Name></Name>
<Cities>
<City></City>
<City></City>
<City></City>
</Cities>
</Region>
<Region>
<Name></Name>
<Cities>
<City></City>
<City></City>
<City></City>
</Cities>
</Region>
</Regions>
</Country>
<Country>
<Code></Code>
<Regions>
<Region>
<Name></Name>
<Cities>
<City></City>
<City></City>
<City></City>
</Cities>
</Region>
<Region>
<Name></Name>
<Cities>
<City></City>
<City></City>
<City></City>
</Cities>
</Region>
</Regions>
</Country>
你应该在你的php中执行此操作:
$url = "URL which gives an xml output";
$xml = new SimpleXMLElement($url);
foreach($xml->children() as $country){
// Query to insert the country into the countries table by $country->Code
foreach($country->Regions as $region){
// Query to insert the region into the regions table by $country->Code and $region->Name
foreach($region->Cities as $city){
// Query to insert the city into the cities table by $country->Code and $region->Name and $city->City
}
}
}