CakePHP Xml 实用程序库触发 DOMDocument 警告
我正在使用 CakePHP 的 Xml 在视图中生成 XML核心库:
I'm generating XML in a view with CakePHP's Xml core library:
$xml = Xml::build($data, array('return' => 'domdocument'));
echo $xml->saveXML();
View 是由控制器提供的数组:
View is fed from the controller with an array:
$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',
),
),
),
),
),
),
),
),
)
);
无论出于何种原因,CakePHP 都会发出这样的内部调用:
For whatever the reason, CakePHP is issuing an internal call like this:
$dom = new DOMDocument;
$key = 'sub4';
$childValue = 'S & T: ERROR';
$dom->createElement($key, $childValue);
... 触发 PHP 警告:
... which triggers a PHP warning:
Warning (2): DOMDocument::createElement(): unterminated entity reference T [CORECakeUtilityXml.php, line 292
... 因为(已记录),DOMDocument::createElement
不转义值.但是,正如测试用例所示,它只在某些节点上执行此操作.
... because (as documented), DOMDocument::createElement
does not escape values. However, it only does it in certain nodes, as the test case illustrates.
是我做错了什么还是我在 CakePHP 中遇到了一个错误?
Am I doing something wrong or I just hit a bug in CakePHP?
推荐答案
问题似乎出在具有属性和值的节点中,因此需要使用 @
语法:
The problem seems to be in nodes that have both attributes and values thus need to use the @
syntax:
'@id' => 'A & B: OK', // <-- Handled as plain text
'name' => 'C & D: OK', // <-- Handled as plain text
'@' => 'S & T: ERROR', // <-- Handled as raw XML
我写了一个小辅助函数:
I've written a little helper function:
protected function escapeXmlValue($value){
return is_null($value) ? null : htmlspecialchars($value, ENT_XML1, 'UTF-8');
}
...并在我创建数组时手动调用它:
... and take care of calling it manually when I create the array:
'@id' => 'A & B: OK',
'name' => 'C & D: OK',
'@' => $this->escapeXmlValue('S & T: NOW WORKS FINE'),
很难说它是错误还是功能,因为 文档 没有提到它.
It's hard to say if it's bug or feature since the documentation doesn't mention it.
相关文章