我在Cake
PHP的
Xml core library视图中生成XML:
$xml = Xml::build($data,array('return' => 'domdocument')); echo $xml->saveXML();
视图由带有阵列的控制器提供:
$this->set( array( 'data' => array( 'root' => array( array( '@id' => 'A & B: OK','name' => 'C & D: OK','sub1' => array( '@id' => 'E & F: OK','name' => 'G & H: OK','sub2' => array( array( '@id' => 'I & J: OK','name' => 'K & L: OK','sub3' => array( '@id' => 'M & N: OK','name' => 'O & P: OK','sub4' => array( '@id' => 'Q & R: OK','@' => 'S & T: ERROR',),) );
$dom = new DOMDocument; $key = 'sub4'; $childValue = 'S & T: ERROR'; $dom->createElement($key,$childValue);
…触发PHP警告:
Warning (2): DOMDocument::createElement(): unterminated entity reference T [CORE\Cake\Utility\Xml.PHP,line 292
…因为(as documented),DOMDocument :: createElement不会转义值.但是,正如测试案例所示,它仅在某些节点中执行.
这可能是PHP的DOMDocument :: createElement()方法中的
bug.你可以避免它.单独创建textnode并将其附加到元素节点.
原文链接:https://www.f2er.com/php/135479.html$dom = new DOMDocument; $dom ->appendChild($dom->createElement('element')) ->appendChild($dom->createTextNode('S & T: ERROR')); var_dump($dom->saveXml());
string(58) "<?xml version="1.0"?> <element>S & T: ERROR</element> "
这是将文本节点添加到DOM的预期方法.您始终创建一个节点(element,text,cdata,…)并将其附加到其父节点.您可以向一个父节点添加多个节点和不同类型的节点.如下例所示:
$dom = new DOMDocument; $p = $dom->appendChild($dom->createElement('p')); $p->appendChild($dom->createTextNode('Hello ')); $b = $p->appendChild($dom->createElement('b')); $b->appendChild($dom->createTextNode('World!')); echo $dom->saveXml();
输出:
<?xml version="1.0"?> <p>Hello <b>World!</b></p>