删除具有异常 XML 的 XML 属性


removing xml attributes with abnormal xml

我创建了一个解析xml文档的ios应用程序。如果用户登录,其信息将添加到 xml 文件中。我希望能够在用户注销或取消登录时删除用户。本质上,我需要弄清楚如何删除如下所示的 xml 对象(在本例中为用户):

<users>
    <user>
        <fname>fname1</fname>
        <lname>lname1</lname>
    </user>
    <user>
        <fname>fname2</fname>
        <lname>lname2</lname>
    </user>
</users>

例如,我可能想根据姓氏删除用户,这在我的情况下始终是唯一的......这是我到目前为止拥有的 php,但我完全愿意接受有关以不同方式执行的建议

$deletefname = $row['fname'];
$deletelname = $row['lname'];
$deleteimageurl = $row['imageURL'];
$xmlUrl = "thefile.xml"; // XML 
$xmlStr = file_get_contents($xmlUrl);
$xml = new SimpleXMLElement($xmlStr);
foreach($xml->users as $user)
{
    if($user[$fname] == $deletefname) {
        $xml=dom_import_simplexml($user);
        $xml->parentNode->removeChild($xml);    
    }
}

$xml->asXML('newfile.xml');
echo $xml;

我对 php 非常糟糕,我从别人那里拿走了这段代码。不是100%确定它是如何工作的。

感谢您的帮助。

<?php 
/*
 * @source_file -- source to your xml document
 * @node_to_remove -- your node
 * Note this will remove an entire user from the source file if the argument (node_to_remove)
   matches a nodes node value
 *
 */
function newFunction($source_file,$node_to_remove) {
    $xml = new DOMDocument();
    $xml->load($source_file);
    $xml->preserveWhiteSpace = false;
    $xml->formatOutput = true; 
    foreach ($xml->getElementsByTagName('users') as $users ) 
    {
        foreach($users->getElementsByTagName('user') as $user) {
            $first_name = $user->getElementsByTagName('fname')->item(0);
            if($first_name->nodeValue == $node_to_remove) {

                $users->removeChild($users->getElementsByTagName('user')->item(0));
            }
        }
    }
    $result = $xml->saveXML();
    return $result;
}

echo newFunction('xml.xml','lname1');
?>

在我开始之前,我会给出通常的警告,即XML文件不是数据库,你应该使用真正的数据库(mysql,sqlite,xml数据库)或至少文件锁定(flock())或原子写入(写入临时文件然后rename()真实名称)。如果不这样做,您将遇到一个请求读取文件而另一个请求正在写入文件的情况,并得到垃圾 XML。

您可以使用 SimpleXMLDOMDocument 来执行此操作,并且对于任何一个,您可以使用 xpath 或迭代。

下面是SimpleXMLElement方法,因为这是您的代码使用的方法。

$sxe = simplexml_load_string($xmlstring);
// XPATH
$matches = $sxe->xpath('/users/user[lname="lname2"]');
foreach ($matches as $match) {
    unset($match[0]);
}
// Iteration--slower, but safer if a part of the path is dynamic (e.g. "lname2")
// because xpath literals are very hard to escape.
// be sure to iterate backwards
for ($i=$sxe->user->count()-1; $i >= 0; --$i) {
    if ($sxe->user[$i]->lname=='lname2') {
        unset($sxe->user[$i]);
    }
}
echo $sxe->asXML();