首页 > 解决方案 > 如何检查提交的元素值是否已经存在?

问题描述

因此,至于作业,我正在编写一个 PHP 熟悉的页面,该页面允许您将订单 ID 提交到 XML 配置,因此它会过滤掉所需的订单。

一切都很好,但我想在配置中已经存在提交的 ID 时提醒用户。

XML 元素

<filter><!-- Copy filter-item and put the order-id in as the value to skip it-->
<filter_item>1142575860</filter_item><filter_item>1142495027</filter_item>
</filter>
    if (isset($_POST['btnAddId'])) 
{
    $addID = $_POST['idFilter'];
    $xml = simplexml_load_file('Config.xml');

    if(empty($addID)) 
    {
        echo '<script> alert("Input value is empty");</script>';
    }
    else if(!is_numeric($addID)) 
    {
        echo '<script> alert("input is not numeric");</script>';
    }
    else if(??)
    {
        echo '<script> alert("ID already exists in the filter");</script>';
    }
    else{    
        
        $orderFilter = $_POST['idFilter'];
        $sxe = new SimpleXMLElement($xml->asXML());
    
        $itemsNode = $sxe->filter;
    
        $itemsNode->addChild('filter_item', $orderFilter);
        $sxe->asXML('Config.xml');
        
        echo $LocScript; 
    }
}   

标签: phpxml

解决方案


您可以使用 XPath 搜索<filter_item>与他们输入的 ID 具有相同内容的元素...

if ( count($xml->xpath('//filter_item[.="'.$addID.'"]')) > 0 )
{
   echo '<script> alert("ID already exists in the filter");</script>';
}

它给出了一个 XPath 表达式(例如)

//filter_item[.="1142495027"]

由于这匹配其中一项,它将返回一个包含 1 项的列表。然后条件count()将触发一个项目已经存在。


推荐阅读