Search code examples
phpxml-parsingsimplexml

Parsing XML element & attributes with PHP


I'm new to PHP and have been trying to write an xml parser, but have hit a wall and it's driving me bonkers!

What I'm trying to do:

  • Write a parser that loops through an XML file accessing both element & attributes, storing the results to a MySQL database.

Sample XML structure:

<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>

Sample PHP code:

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; 

}}

Result: Database cleared, and all of the items were imported correctly!

In reality no new rows are added to the database. This code does work fine for accessing elements only; but no longer works when trying to access both elements and attributes.

Other info: Currently using PHP 5.4

Any help would be greatly appreciated!


Solution

  • I found two issues in your code, first your xml is missing ending players tag in the second last line.

    Second you can not directly access player tag, you need to go through players tag first.

    You can simply replace:

     foreach ($xml->player as $player) {
    

    to

     foreach ($xml->players->player as $player) {