我是PHP的新手,并且一直在尝试编写一个xml解析器,但是已经碰壁了,这让我疯狂了!
我正在尝试做什么:
示例XML结构:
<playerdata>
<players>
<player>
<playername id="1">Human</playername>
<allianceid id="18" />
<allianceroleid id="22" />
<race id="1" />
</player>
<player>
<playername id="2">Machine</playername>
<allianceid id="42" />
<allianceroleid id="86" />
<race id="3" />
</player>
<player>
<playername id="3">Alien</playername>
<allianceid id="1" />
<allianceroleid id="2354" />
<race id="1" />
</player>
</players>
</playerdata>
示例PHP代码:
if (isset($_FILES['xml'])) {
if ($_FILES['xml']['size'] > 0) {
$file = $_FILES['xml']['tmp_name'];
mysqli_query($dbconnect,"TRUNCATE TABLE players") or die ("Error in query: $insert. ".mysqli_error($dbconnect));
$xml = simplexml_load_file($file);
$count = 0;
foreach ($xml->player as $player) {
$player_id = mysqli_real_escape_string($dbconnect,$player->playername['id']);
$player_name = mysqli_real_escape_string($dbconnect,$player->playername);
$alliance_id = mysqli_real_escape_string($dbconnect,$player->allianceid['id']);
$alliance_role_id = mysqli_real_escape_string($dbconnect,$player->allianceroleid['id']);
$player_race_id = mysqli_real_escape_string($dbconnect,$player->race['id']);
// print $player_id . "<br />";
mysqli_query($dbconnect,"INSERT INTO players (player_id, player_name, alliance_id, alliance_role_id, player_race_id)
VALUES ('$player_id', '$player_name', '$alliance_id', '$alliance_role_id', '$player_race_id')") or die ("Error in query: $insert. ".mysqli_error($dbconnect));
$count++;
}
//redirect
header('Location: index.php?success=1?inserts=' . $count . ''); die;
}}
结果:数据库已清除,所有项目均已正确导入!
实际上,没有新行添加到数据库中。此代码仅适用于访问元素;但在尝试访问元素和属性时不再有效。
其他信息:目前正在使用PHP 5.4
非常感谢任何帮助!
答案 0 :(得分:0)
您可以使用以下代码来解析xml。
$xml = simplexml_load_file($file);
xml_parse_into_struct($xml, $simple, $vals, $index);
这将为您提供$ vals中的数组
echo "\nVals array\n";
print_r($vals);
做你想做的事情
答案 1 :(得分:0)
我在你的代码中发现了两个问题,首先你的xml在最后一行中缺少结束玩家标记。
其次,你不能直接访问玩家标签,你需要首先通过玩家标签。
您可以简单地替换:
foreach ($xml->player as $player) {
到
foreach ($xml->players->player as $player) {