How to write CDATA using SimpleXmlElement?

后端 未结 5 763
情话喂你
情话喂你 2020-11-27 15:08

I have this code to create and update xml file:

\');
$xml->title          


        
5条回答
  •  被撕碎了的回忆
    2020-11-27 15:59

    Here's my version of this class that has a quick addChildWithCDATA method, based on your answer:

        Class SimpleXMLElementExtended extends SimpleXMLElement {
    
      /**
       * Adds a child with $value inside CDATA
       * @param unknown $name
       * @param unknown $value
       */
      public function addChildWithCDATA($name, $value = NULL) {
        $new_child = $this->addChild($name);
    
        if ($new_child !== NULL) {
          $node = dom_import_simplexml($new_child);
          $no   = $node->ownerDocument;
          $node->appendChild($no->createCDATASection($value));
        }
    
        return $new_child;
      }
    }
    

    Simply use it like that:

    $node = new SimpleXMLElementExtended();
    $node->addChildWithCDATA('title', 'Text that can contain any unsafe XML charachters like & and <>');
    

提交回复
热议问题