How to remove a node if it exists with simpleXML

2019-09-05 23:59发布

问题:

So I know the exact path the node I would be attempting to remove. I am iterating through several xml files to update some of the content. In order to add some of the new content in, I must first delete the content that already exists.

Here is the code I attempted to use, but I'm receiving a Parse error: syntax error, unexpected T_UNSET

public function hint_insert() {

    foreach($this->hints as $key => $value) {

        $filename = $this->get_qid_filename($key);

        echo "$key - $filename - $value[0]<br>";

        //insert hint within right node using simplexml
        $xml = simplexml_load_file($filename);

        foreach ($xml->PrintQuestion as $PrintQuestion) {

            if (unset($xml->PrintQuestion->content->multichoice->feedback->hint->Passage)) {

                $xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]);

            } else {

                $xml->PrintQuestion->content->multichoice->feedback->hint->addChild('Passage', $value[0]);

            }

        }

    }

回答1:

unset is a language construct, and you cannot use it in an if statement. If you use it outside an if statement / don't expect it to return anything you should be fine though.