SimpleXML 不能很好地处理 CDATA。如果要编写 CDATA,则需要使用DOM对象。例如:
$xml = new DOMDocument();
$xml->load('demo.xml');
$i = 2;
foreach ($xml->getElementsByTagName('Page') as $page) {
if ($page->attributes->getNamedItem('id')->value == $i) {
$da = 'data';
$text = 'helloworld';
$data = $xml->createElement($da);
$data->appendChild($xml->createCDATASection($text));
$page->appendChild($data);
}
}
如果您想继续使用 SimpleXML,您可以只加载您想要写入 CDATA 的元素作为 DOM 对象。
$xml = simplexml_load_file('demo.xml');
$i = 2;
foreach ($xml->Page as $page) {
if ($page['id'] == $i) {
$da = 'data';
$text = 'helloworld';
$page->$da = '';
$node = dom_import_simplexml($page->$da);
$dom = $node->ownerDocument;
$node->appendChild($dom->createCDATASection($text));
}
}
$xml->asXML('demo.xml');