【问题标题】:loop through XML elements with php, find match and change child elements innerHTML使用 php 循环遍历 XML 元素,查找匹配并更改子元素 innerHTML
【发布时间】:2017-04-20 01:11:08
【问题描述】:

用户可以在登录时更改页面上的用户名。当他登录时,$_SESSION['userSession'] 设置为他的 user_id 值 (1, 2, 3, . ..)。

除了数据库存储,一些用户信息也存储在一个 XML 文件中。当用户更改他的用户名时,我遇到了问题

  • 识别匹配的 XML 元素 (子 'user_id' 的元素 'account' 包含 innerHtml == $_SESSION['userSession'])

  • 并更改其他子项的特定 XML 元素值 (更改元素 'account' 的子 'username' 的 innerHtml,该元素有另一个子 'user_id' 谁是 innerHtml == $_SESSION['userSession'])

现在我的代码只适用于第一个用户,它的 user_id 为 '1' - 所以我想我需要对所有帐户元素进行某种循环。这就是我卡住的地方。 我的当前 PHP 代码是:

        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());

XML 文件 看起来像:

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

有人可以向我解释一下,我可以如何遍历所有帐户元素以找到匹配项并更改其他孩子的内部 html,好吗?

提前致谢!

【问题讨论】:

    标签: php xml loops innerhtml


    【解决方案1】:

    这是一个正确的代码:

    $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());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多