如何使用 php 删除 xml 上的特定元素
我的.xml
<usr>
<uid trk= "1234">
<deleteThis>
<mychild>here</mychild>
<anotherchild>here</anotherchild>
</deleteThis>
</uid>
</usr>
我想删除“deleteThis”元素及其子元素
结果:
<usr>
<uid trk= "1234">
</uid>
</usr>
这是我的非工作代码
index.php
$xml = new DOMDocument;
$xml->load('my.xml');
$thedocument = $xml->documentElement;
$list = $thedocument->getElementsByTagName('uid');
foreach ($list as $domElement){
$attrValue = $domElement->getAttribute('trk');
if ($attrValue == "1234") { //if <uid trk= "1234">
$valY = $domElement->getElementsByTagName('deleteThis');
$thedocument->removeChild($valY);
}
}
$xml->save("my.xml");
好像没有找到节点。
if ($attrValue == "1234") { //if <uid trk= "1234">
$valY = $domElement->getElementsByTagName('deleteThis');
//$valY is a DOMNodeList, that you happen to know there is only one doesnt matter
foreach($valY as $delnode){
$delnode->parentNode->removeChild( $delnode);
}
}
使用 php 在 XML 中获取完整的 Curd 操作,请点击此链接 https://soronix.com/category/php/projects/xml-curd-php/
要从 XML 中删除数据,请尝试此代码
<?php
$id = $_GET['id'];
$employee = simplexml_load_file('employee.xml');
//we're are going to create iterator to assign to each user
$index = 0;
$i = 0;
foreach($employee->emp as $emp){
if($emp->id == $id){
$index = $i;
break;
}
$i++;
}
unset($employee->emp[$index]);
file_put_contents('employee.xml', $employee->asXML());
$_SESSION['message'] = 'Employee deleted successfully';
header('location: '.$_SERVER['HTTP_REFERER']);