0

我想删除:

<newWord>
    <Heb>צהוב</Heb>
    <Eng>yellow</Eng>
 </newWord>

从:

<?xml version="1.0" encoding="UTF-8"?>
<xml>
  <newWord>
    <Heb>מילה ראשונה</Heb>
    <Eng>first word</Eng>
  </newWord>
  <newWord>
    <Heb>צהוב</Heb>
    <Eng>yellow</Eng>
  </newWord>
</xml>

所以输出将是:

<?xml version="1.0" encoding="UTF-8"?>
    <xml>
      <newWord>
        <Heb>מילה ראשונה</Heb>
        <Eng>first word</Eng>
      </newWord>
    </xml>

我尝试找到标签<newWord>,然后去它的孩子, <Eng>yellow</Eng> 如果我找到它,$searchString = 'yellow';我应该去它的父母并删除元素<newWord>

我尝试通过以下代码执行此操作,但我不知道如何去 <newWord>. 非常感谢您的帮助。

这是我的代码:

<?php 
$del=true;
        if ($del==TRUE){
                $searchString = 'yellow';
                header('Content-type: text/xml; charset=utf-8');
                $xml = simplexml_load_file('./Dictionary_user.xml');



                foreach($xml->children() as $child){
                  if($child->getName() == "newWord") {
                      if($searchString == $child['Eng']) {
                        $dom->parentNode->removeChild($xml);
                    } else {
                        echo('no match found resualt');
                    }
                  }
                }

                $dom = new DOMDocument; 
                $dom->preserveWhiteSpace = FALSE;
                $dom->formatOutput = true;
                $dom->load('Dictionary_user.xml');

                $dom->save("Dictionary_user.xml");
                $dom->saveXML();
                header('Location: http://127.0.0.1/www/www1/ajax/ajax4/workwell/popus1.html');
}
?>
4

2 回答 2

0

在这条线上

if($searchString == $child['Eng']) {

您正在尝试比较子节点的主体,但它不会自动转换为字符串。它仍然是 a SimpleXMLElement object,所以比较失败。

尝试将其显式转换为字符串以获取标签的正文。

if($searchString == (string)$child['Eng']) {
于 2012-08-28T12:20:42.047 回答
0

试试这个:

$searchString = 'yellow';
$xml = simplexml_load_file('./Dictionary_user.xml');

foreach($xml->children() as $child){    
  if($child->getName() == "newWord") {
    if($child->Eng == $searchString){
        $dom = dom_import_simplexml($child);
        $dom->parentNode->removeChild($dom);
    }
  }
}

echo $xml->asXML();
于 2012-08-28T12:22:26.853 回答