在php中删除带有simplexml的节点

时间:2013-12-27 14:46:54

标签: php xml

我有一个包含服务器的xml文件。

<?xml version="1.0" encoding="UTF-8"?>
<servers>
   <server>
      <location>Belgium</location>
      <ip>192.168.0.1</ip>
      <port>8080</port>
      <crt></crt>
   </server>
   <server>
      <location>Fhoto</location>
      <ip>192.168.0.5</ip>
      <port>7841</port>
      <crt>http://127.0.0.1/serv.crt</crt>
   </server>
   <server>
      <location>TestingPanel</location>
      <ip>192.168.1.2</ip>
      <port>6969</port>
      <crt>http://testingpanel.com/server.crt</crt>
   </server>
   <server>
      <location>TestingPanel2</location>
      <ip>192.168.1.3</ip>
      <port>6968</port>
      <crt>http://testingpanel.com/server1.crt</crt>
   </server>
</servers>

我制作了一个可以在文件中添加服务器的php页面,效果很好。现在我想创建一个可以输入IP的表单,php脚本应该删除整个节点。

所以举个例子。我有一个带有文本框的表单,然后输入&#34; 192.168.0.1&#34;。我希望它删除它:

   <server>
      <location>Belgium</location>
      <ip>192.168.0.1</ip>
      <port>8080</port>
      <crt></crt>
   </server>

到目前为止我有这个(基本上没什么):

if (isset($_POST["deleteServer"])) { 
    //do processing
}

请指导我正确的方向,因为我不知道如何做到这一点。提前谢谢!

2 个答案:

答案 0 :(得分:1)

我建议使用DomDocument和Xpath来查找节点:

$xml = new DOMDocument();
$xml->load($filePath);
$xpathXml = new DOMXPath($xml);

接下来你需要做的是找到节点:

$elements = $xpathXml->query("//Server[ip="$yourIp"]);

并删除从父节点找到的元素:

foreach ($elements as $element) {
  $element->parentNode->removeChild($element);
}

答案 1 :(得分:1)

使用simplexml_load_file()加载文件,循环通过<server>节点并检查IP是否等于给定的IP。

如果是,请使用unset()上的self-reference of the SimpleXMLElement node将其删除:

$xml = simplexml_load_file('file.xml');
foreach ($xml as $key => $server) {
    if ( $server->ip != '192.168.0.1') {
        continue;
    }
    unset($server[0]);
}

Demo.