gpt4 book ai didi

php - 循环遍历xml并将数据存储到MySQL表中

转载 作者:行者123 更新时间:2023-11-29 17:36:28 25 4
gpt4 key购买 nike

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

最佳答案

如果您的 .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
}
}
}

关于php - 循环遍历xml并将数据存储到MySQL表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50246405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com