Search code examples
phpxmlloopsinnerhtml

loop through XML elements with php, find match and change child elements innerHTML


A user has the ability to change his username on the page while he is logged in. As he is logged in, there is $_SESSION['userSession'] set to be his user_id value (1, 2, 3, ... ).

Apart from database-storing some user-informations are stored in an XML file, too.When the user changes his username, I have issues

  • to identify the matching XMLelement (element 'account' who's child 'user_id' contains the innerHtml == $_SESSION['userSession'])

  • and change that specific XMLelements other childs value (change the innerHtml of the child 'username' of the element 'account' which has another child 'user_id' who's innerHtml == $_SESSION['userSession'])

Right now my code works only for the first user, which has user_id '1' - so I need to do some sort of loop through all account elements, i guess. And this is where I got stuck. My current PHP-code is:

        include '../php/dbconnect.php';
        $DBcon->query("UPDATE tbl_users SET username = '$newuname' WHERE user_id=".$_SESSION['userSession']);
        $DBcon->close();

        $xml = simplexml_load_file('../xml/accounts.xml');
        $account = $xml->account;
            if($account->user_id == $_SESSION['userSession']) {
                $account->username = $newuname;
            } else {
            }
        file_put_contents('../xml/accounts.xml', $xml->asXML());

The XML-File looks like:

<data>

    <account>
        <username>KingKarl</username>
        <user_id>1</user_id>
        <blogname>YummyYummy</blogname>
    </account>

    <account>
        <username>MacMarty</username>
        <user_id>2</user_id>
        <blogname>FreaksOnTour</blogname>
    </account>

    <account>
        <companyname>BungeeTours</companyname>
        <user_id>3</user_id>
        <blogname>FreeFalling</blogname>
    </account>


</data>

Can someone explain to me, how I can loop through all the account elements to find a match and change the other childs inner html, please?

Thanks in advance!


Solution

  • Here's a proper code:

    $xml = simplexml_load_file('../xml/accounts.xml');
    // iterate over each `$xml` node which is `account`
    foreach ($xml as $account) {
        // if current account user_id is found - change value
        if($account->user_id == $_SESSION['userSession']) {
            $account->username = $newuname;
    
            // use break so as not to check other nodes
            break;
        } 
        // empty `else` part is useless, omit it
    }
    file_put_contents('../xml/accounts.xml', $xml->asXML());