代码之家  ›  专栏  ›  技术社区  ›  Warrior

用CDATA编辑xml文件

  •  2
  • Warrior  · 技术社区  · 15 年前

    $xml = simplexml_load_file($xmlfile) or die ("Unable to load XML file!"); 
    $event->title = $newtitle;
    $event->description = $newdescription;
    file_put_contents($xmlfile, $xml->asXML());
    

    我想在描述中添加一个CDATA

    $event->description = '<![CDATA['.$newdescription.']]>';
    

    但是在xml中 < > &lt; &gt; 我怎样才能留住 CDATA 原来如此。还有其他的编辑方法吗。提前谢谢。

    实际上我想编辑这个xml文件

    <events date="06-11-2010">
        <event id="8">
          <title>Proin porttitor sollicitudin augue</title>
          <description><![CDATA[Lorem  nunc.]]></description>
        </event>
      </events>
      <events date="16-11-2010">
        <event id="4">
          <title>uis aliquam dapibus</title>
          <description><![CDATA[consequat vel, pulvinar.</createCDATASection></description>
        </event>
      <event id="1"><title>You can use HTML and CSS</title>
      <description><![CDATA[Lorem ipsum dolor sit amet]]></description></event></events>
    

    3 回复  |  直到 15 年前
        1
  •  3
  •   cEz    15 年前

    我认为你需要使用 DOM 当你的需求变得更加复杂 简单的 createCDATASection .

    下面是一个基本示例:

    $dom=new DOMDocument();
    $xml='data.xml';
    $dom->load($xml);
    $cdata=$dom->createCDATASection('<p>Foo</p>');
    foreach ($dom->getElementsByTagName('item') as $item) {
        $item->getElementsByTagName('content')->item(0)->appendChild($cdata);
    }
    
    $dom->save($xml);
    

    <?xml version="1.0" encoding="utf-8"?>
    <data>
        <item>
            <title>Test</title>
            <content><![CDATA[<p>Foo</p>]]></content>
        </item>
    </data>
    

    $dom=new DOMDocument();
    $dom->validateOnParse = true;
    
    $xml='data.xml';
    $dom->load($xml);
    
    // Unless the ID attribute is recognised
    foreach ($dom->getElementsByTagName('event') as $event) { 
        $event->setIdAttribute('id', true);
    }
    
    $event = $dom->getElementById("1");
    foreach ($event->getElementsByTagName('description') as $description) {
        $cdata=$dom->createCDATASection('<p>'. $description->nodeValue .'</p>');
        $description->replaceChild($cdata, $description->childNodes->item(0));
    }
    
    $dom->save($xml);
    
        2
  •  2
  •   Wrikken    15 年前

    基本上, SimpleXML CDATA 节点不存在。但如果你真的需要它们,就不能在 简单XML ,使用另一个选项,如 DOMDocument 它的功能 createCDATASection()

        3
  •  -2
  •   MatTheCat    15 年前

    $xml = simplexml_load_file($xmlfile,'SimpleXMLElement', LIBXML_NOCDATA);
    

    ?

    推荐文章