Php 如果xml元素存在,请退出或跳过
我如何使用php dom在xml中检查,如果某个特定元素存在,它就不应该重复它。例如,如果我有一个“activity”元素,它应该对照xml文件检查该元素是否存在,如果存在,它将不会再次创建它 换句话说,我只想在开始时创建元素“activity”一次,但其他元素可以重复出现 这是php代码:Php 如果xml元素存在,请退出或跳过,php,xml,domdocument,Php,Xml,Domdocument,我如何使用php dom在xml中检查,如果某个特定元素存在,它就不应该重复它。例如,如果我有一个“activity”元素,它应该对照xml文件检查该元素是否存在,如果存在,它将不会再次创建它 换句话说,我只想在开始时创建元素“activity”一次,但其他元素可以重复出现 这是php代码: <?php header("Location: index.php"); $xmldoc = new DOMDocument(); if(file_exists('sampl
<?php
header("Location: index.php");
$xmldoc = new DOMDocument();
if(file_exists('sample.xml')){
$xmldoc->load('sample.xml');
} else {
$xmldoc->loadXML('<root/>');
}
$newAct = $_POST['activity'];
$newTime = $_POST['time'];
$root = $xmldoc->firstChild;
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText = $xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$newElementE = $xmldoc->createElement('time');
$root->appendChild($newElementE);
$newTextE = $xmldoc->createTextNode($newTime);
$newElementE->appendChild($newTextE);
$xml->formatOutput = true;
$xmldoc->save('sample.xml');
?>
load('sample.xml');
}否则{
$xmldoc->loadXML(“”);
}
$newAct=$_POST['activity'];
$newTime=$_POST['time'];
$root=$xmldoc->firstChild;
$newElement=$xmldoc->createElement('activity');
$root->appendChild($newElement);
$newText=$xmldoc->createTextNode($newAct);
$newElement->appendChild($newText);
$newElementE=$xmldoc->createElement('time');
$root->appendChild($newElementE);
$newTextE=$xmldoc->createTextNode($newTime);
$newElementE->appendChild($newtext);
$xml->formatOutput=true;
$xmldoc->save('sample.xml');
?>
您应该将“位置”标题放在脚本末尾。
if ($xmldoc->getElementsByTagName("activity")->length == 0) {
$newElement = $xmldoc->createElement('activity');
$root->appendChild($newElement);
}