: str_replace(): Passing null to parameter #2 ($replace) of type array|string is deprecated in
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @license https://opensource.org/licenses/mit-license.php MIT License
use Cake\Utility\Exception\XmlException;
* XML handling for CakePHP.
* The methods in these classes enable the datasources that use XML to work.
* Initialize SimpleXMLElement or DOMDocument from a given XML string, file path, URL or array.
* Building XML from a string:
* $xml = Xml::build('<example>text</example>');
* Building XML from string (output DOMDocument):
* $xml = Xml::build('<example>text</example>', ['return' => 'domdocument']);
* Building XML from a file path:
* $xml = Xml::build('/path/to/an/xml/file.xml');
* Building XML from a remote URL:
* $response = $http->get('http://example.com/example.xml');
* $xml = Xml::build($response->getStringBody());
* Building from an array:
* 'name' => 'enhancement'
* $xml = Xml::build($value);
* When building XML from an array ensure that there is only one top level element.
* - `return` Can be 'simplexml' to return object of SimpleXMLElement or 'domdocument' to return DOMDocument.
* - `loadEntities` Defaults to false. Set to true to enable loading of `<!ENTITY` definitions. This
* is disabled by default for security reasons.
* - `readFile` Set to false to disable file reading. This is important to disable when
* putting user data into Xml::build(). If enabled local files will be read if they exist.
* Defaults to true for backwards compatibility reasons.
* - `parseHuge` Enable the `LIBXML_PARSEHUGE` flag.
* If using array as input, you can pass `options` from Xml::fromArray.
* @param string|array|object $input XML string, a path to a file, a URL or an array
* @param array $options The options to use
* @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
* @throws \Cake\Utility\Exception\XmlException
public static function build($input, array $options = [])
if (is_array($input) || is_object($input)) {
return static::fromArray($input, $options);
if (strpos($input, '<') !== false) {
return static::_loadXml($input, $options);
if ($options['readFile'] && file_exists($input)) {
return static::_loadXml(file_get_contents($input), $options);
if (!is_string($input)) {
throw new XmlException("Invalid input. {$type} cannot be parsed as XML.");
if (strpos($input, '<') !== false) {
return static::_loadXml($input, $options);
throw new XmlException('XML cannot be read.');
* Parse the input data and create either a SimpleXmlElement object or a DOMDocument.
* @param string $input The input to load.
* @param array $options The options to use. See Xml::build()
* @return \SimpleXMLElement|\DOMDocument
* @throws \Cake\Utility\Exception\XmlException
protected static function _loadXml($input, $options)
$hasDisable = function_exists('libxml_disable_entity_loader');
$internalErrors = libxml_use_internal_errors(true);
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(true);
if (!empty($options['parseHuge'])) {
$flags |= LIBXML_PARSEHUGE;
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
$flags |= LIBXML_NOCDATA;
$xml = new SimpleXMLElement($input, $flags);
$xml = new DOMDocument();
$xml->loadXML($input, $flags);
throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(false);
libxml_use_internal_errors($internalErrors);
* Parse the input html string and create either a SimpleXmlElement object or a DOMDocument.
* @param string $input The input html string to load.
* @param array $options The options to use. See Xml::build()
* @return \SimpleXMLElement|\DOMDocument
* @throws \Cake\Utility\Exception\XmlException
public static function loadHtml($input, $options = [])
$hasDisable = function_exists('libxml_disable_entity_loader');
$internalErrors = libxml_use_internal_errors(true);
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(true);
if (!empty($options['parseHuge'])) {
$flags |= LIBXML_PARSEHUGE;
$xml = new DOMDocument();
$xml->loadHTML($input, $flags);
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
$flags |= LIBXML_NOCDATA;
$xml = simplexml_import_dom($xml);
throw new XmlException('Xml cannot be read. ' . $e->getMessage(), null, $e);
if ($hasDisable && !$options['loadEntities']) {
libxml_disable_entity_loader(false);
libxml_use_internal_errors($internalErrors);
* Transform an array into a SimpleXMLElement
* - `format` If create childs ('tags') or attributes ('attributes').
* - `pretty` Returns formatted Xml when set to `true`. Defaults to `false`
* - `version` Version of XML document. Default is 1.0.
* - `encoding` Encoding of XML document. If null remove from XML header. Default is the some of application.
* - `return` If return object of SimpleXMLElement ('simplexml') or DOMDocument ('domdocument'). Default is SimpleXMLElement.
* Using the following data:
* Calling `Xml::fromArray($value, 'tags');` Will generate:
* `<root><tag><id>1</id><value>defect</value>description</tag></root>`
* And calling `Xml::fromArray($value, 'attributes');` Will generate:
* `<root><tag id="1" value="defect">description</tag></root>`
* @param array|object $input Array with data or a collection instance.
* @param array $options The options to use.
* @return \SimpleXMLElement|\DOMDocument SimpleXMLElement or DOMDocument
* @throws \Cake\Utility\Exception\XmlException
public static function fromArray($input, $options = [])
if (is_object($input) && method_exists($input, 'toArray') && is_callable([$input, 'toArray'])) {
$input = call_user_func([$input, 'toArray']);
if (!is_array($input) || count($input) !== 1) {
throw new XmlException('Invalid input.');
throw new XmlException('The key of input must be alphanumeric');
if (!is_array($options)) {
$options = ['format' => (string)$options];
'encoding' => mb_internal_encoding(),
$dom = new DOMDocument($options['version'], $options['encoding']);
if ($options['pretty']) {
$dom->formatOutput = true;
self::_fromArray($dom, $dom, $input, $options['format']);
$options['return'] = strtolower($options['return']);
if ($options['return'] === 'simplexml' || $options['return'] === 'simplexmlelement') {
return new SimpleXMLElement($dom->saveXML());
* Recursive method to create childs from array
* @param \DOMDocument $dom Handler to DOMDocument
* @param \DOMDocument|\DOMElement $node Handler to DOMElement (child)
* @param array $data Array of data to append to the $node.
* @param string $format Either 'attributes' or 'tags'. This determines where nested keys go.
* @throws \Cake\Utility\Exception\XmlException
protected static function _fromArray($dom, $node, &$data, $format)
if (empty($data) || !is_array($data)) {
foreach ($data as $key => $value) {
if (is_object($value) && method_exists($value, 'toArray') && is_callable([$value, 'toArray'])) {
$value = call_user_func([$value, 'toArray']);
} elseif ($value === null) {
$isNamespace = strpos($key, 'xmlns:');
if ($isNamespace !== false) {
$node->setAttributeNS('http://www.w3.org/2000/xmlns/', $key, (string)$value);
if ($key[0] !== '@' && $format === 'tags') {
if (!is_numeric($value)) {
// Escape special characters
// https://www.w3.org/TR/REC-xml/#syntax
// https://bugs.php.net/bug.php?id=36795
$child = $dom->createElement($key, '');
$child->appendChild(new DOMText((string)$value));
$child = $dom->createElement($key, $value);
$node->appendChild($child);
$attribute = $dom->createAttribute($key);
$attribute->appendChild($dom->createTextNode((string)$value));
$node->appendChild($attribute);
throw new XmlException('Invalid array');
if (is_numeric(implode('', array_keys($value)))) {
foreach ($value as $item) {
$itemData = compact('dom', 'node', 'key', 'format');
$itemData['value'] = $item;
static::_createChild($itemData);
static::_createChild(compact('dom', 'node', 'key', 'value', 'format'));
throw new XmlException('Invalid array');
* Helper to _fromArray(). It will create childs of arrays
* @param array $data Array with information to create childs
protected static function _createChild($data)
$format = $data['format'];
$childNS = $childValue = null;
if (is_object($value) && method_exists($value, 'toArray') && is_callable([$value, 'toArray'])) {
$value = call_user_func([$value, 'toArray']);
if (isset($value['@'])) {
$childValue = (string)$value['@'];
if (isset($value['xmlns:'])) {
$childNS = $value['xmlns:'];
} elseif (!empty($value) || $value === 0 || $value === '0') {
$childValue = (string)$value;
$child = $dom->createElement($key);
if ($childValue !== null) {
$child->appendChild($dom->createTextNode($childValue));
$child->setAttribute('xmlns', $childNS);
static::_fromArray($dom, $child, $value, $format);
$node->appendChild($child);
* Returns this XML structure as an array.
* @param \SimpleXMLElement|\DOMDocument|\DOMNode $obj SimpleXMLElement, DOMDocument or DOMNode instance
* @return array Array representation of the XML structure.
* @throws \Cake\Utility\Exception\XmlException
public static function toArray($obj)
if ($obj instanceof DOMNode) {
$obj = simplexml_import_dom($obj);
if (!($obj instanceof SimpleXMLElement)) {
throw new XmlException('The input is not instance of SimpleXMLElement, DOMDocument or DOMNode.');
$namespaces = array_merge(['' => ''], $obj->getNamespaces(true));
static::_toArray($obj, $result, '', array_keys($namespaces));
* Recursive method to toArray
* @param \SimpleXMLElement $xml SimpleXMLElement object
* @param array $parentData Parent array with data
* @param string $ns Namespace of current child
* @param string[] $namespaces List of namespaces in XML
protected static function _toArray($xml, &$parentData, $ns, $namespaces)
foreach ($namespaces as $namespace) {
foreach ($xml->attributes($namespace, true) as $key => $value) {
if (!empty($namespace)) {
$key = $namespace . ':' . $key;
$data['@' . $key] = (string)$value;
foreach ($xml->children($namespace, true) as $child) {
static::_toArray($child, $data, $namespace, $namespaces);
$asString = trim((string)$xml);
} elseif (strlen($asString) > 0) {
$name = $ns . $xml->getName();
if (isset($parentData[$name])) {
if (!is_array($parentData[$name]) || !isset($parentData[$name][0])) {
$parentData[$name] = [$parentData[$name]];
$parentData[$name][] = $data;
$parentData[$name] = $data;