【问题标题】:unset() Not Working For XMLunset() 不适用于 XML
【发布时间】:2014-04-21 08:57:53
【问题描述】:

目前我正在使用 unset() 删除 simpleXML 中的父节点,并将其写回 XML 文件

我试了这段代码,前段时间还可以用,清理完代码后我找不到为什么突然不能用了,

我采取的调试方法:文件可以访问,我可以进入循环和if语句,文件被保存(notepad++要求我重新加载),但<systemInfo></systemInfo>没有被删除

这是我的示例代码:

        $userorig = $_POST['user'];
        $userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file

        foreach ($userinfos->userinfo->account as $account) 
        {       
            // Checks if the user in this iteration of the loop is the same as $userorig (the user i want to find)
            if($account->user == $userorig)
            {
                echo "hello";
                $rootSystem = $account->systemInfo;
                unset($rootSystem);
            }
        }
        $userinfos->saveXML('userInfo.xml');

我的 XML 文件:

<userinfos>
  <userinfo>
   <account>
     <user>TIGERBOY-PC</user>
     <toDump>2014-03-15 03:20:44</toDump>
     <toDumpDone>0</toDumpDone>
     <initialCheck>0</initialCheck>
     <lastChecked>2014-03-16 07:12:17</lastChecked>
     <alert>1</alert>
     <systemInfo>
          ... (many nodes and sub nodes here) ...
     </systemInfo>
   </account>
  </userinfo>
</userinfos>

【问题讨论】:

    标签: php xml debugging simplexml unset


    【解决方案1】:

    它又工作了,抱歉,我不知道它为什么工作,我一直在多个实例上运行它,现在它工作了,程序有奇怪的行为,但尝试了大约 15 次,它完成了它的工作

    【讨论】:

      【解决方案2】:

      不要遍历整个xml,而是使用xpath来选择节点:

      $userorig = $_POST['user'];
      $userinfos = simplexml_load_file('userInfo.xml'); // Opens the user XML file
      
      $deletethisuser = $userinfos->xpath("/userinfos/userinfo/account[user = '$userorig']/systemInfo")[0];
      unset($deletethisuser[0]);
      

      评论:

      xpath... 行中的 [0] 需要 PHP >= 5.4,以防您在较低版本上运行,请更新或继续:

      $deletethisuser = $userinfos->xpath("/userinfos/userinfo/account[user = '$userorig']/systemInfo");
      unset($deletethisuser[0][0]);
      

      建议阅读:hakre 在此线程中的回答:Remove a child with a specific attribute, in SimpleXML for PHP

      【讨论】:

      • 我真的需要迭代整个 XML 来找到用户,我也编辑值并运行它们,这段代码是 500 行的一个非常短的版本 =)) ,所以 foreach顺便说一句,循环帮助我获得更简洁的代码,谢谢你的提示,我从来不知道 xpath,我只是毫无头绪地使用 XML(因为使用那里的函数更容易解析)
      • @SaggerAl-Saadi 您当然可以选择带有xpath的节点并进行更改,无需迭代。
      猜你喜欢
      • 2011-11-16
      • 2020-05-24
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-24
      • 2020-07-25
      • 1970-01-01
      相关资源
      最近更新 更多