cakephp/cakephp · error · SerializationFailureException

XML serialization of View data failed.

Error message

XML serialization of View data failed.

What it means

XmlView renders a response as XML by converting the view's serialized data via Xml::fromArray() and calling saveXML(). If saveXML() returns false, the DOM document could not be serialized (structurally invalid XML document), and CakePHP throws SerializationFailureException. This is an internal-invariant check: fromArray already validates array shape, so false indicates an unexpected low-level serialization failure.

Solutions

  1. Inspect the data passed to the view (set with $this->set(...)) and ensure top-level keys and array shapes are XML-serializable via Xml::fromArray().
  2. Sanitize array keys to valid XML element names (letters/underscores, no spaces or invalid chars) before setting view data.
  3. Add a manual Xml::fromArray($data)->saveXML() check in development to see the underlying DOM error.
  4. If XML output is not actually required, remove the .xml extension usage or restrict serialization types to json.

Example fix

// before
$this->set('data', $rows);
$this->viewBuilder()->setClassName('Cake.View.Xml');
// after
$this->set('data', array_map(function ($r) {
    unset($r['invalid key!']); // or rename to valid element name
    return $r;
}, $rows));
$this->viewBuilder()->setClassName('Cake.View.Xml');
Defensive patterns

Strategy: try-catch

Validate before calling

use Cake\Utility\Xml;
try {
    Xml::fromArray($data)->saveXML();
} catch (\Throwable $e) {
    // keys/shape not XML-serializable — sanitize before rendering
}

Type guard

function isXmlSerializable(array $data): bool {
    foreach (array_keys($data) as $k) {
        if (!is_string($k) || !preg_match('/^[A-Za-z_][A-Za-z0-9_.-]*$/', $k)) {
            return false;
        }
    }
    return true;
}

Try / catch

try {
    $this->render('xml');
} catch (\Cake\View\Exception\SerializationFailureException $e) {
    return $this->getResponse()->withStatus(500)
        ->withStringBody('XML serialization failed');
}

Prevention

When it happens

Trigger: A controller using static::serializationType('xml') / RequestHandler with XML extension where the data array contains structures Xml::fromArray cannot turn into a valid DOM document (e.g. invalid element names, mixed/nested content that yields an unsaveable document).

Common situations: Serving API endpoints as XML where entity data contains keys that are invalid XML tag names (spaces, leading digits, special chars) or deeply inconsistent arrays; users hitting a URL with the .xml extension on data intended for JSON.

Understand the failure class

Background: "JSON serialization failed", "not JSON serializable", "Failed to serialize": why JSON marshaling errors happen and how to fix them — this error's family across 46 libraries.

Related errors


AI-assisted analysis of cakephp/cakephp@1128eba9b0 (2026-09-12). Data as JSON: /api/errors/0a54b9fd5e1243a9. Report an issue: GitHub.

Appendix: source

Thrown at src/View/XmlView.php:157

                $data !== null &&
                (!is_array($data) || Hash::numeric(array_keys($data)))
            ) {
                $data = [$rootNode => [$serialize => $data]];
            }
        }

        $options = $this->getConfig('xmlOptions', []);
        if (Configure::read('debug')) {
            $options['pretty'] = true;
        }

        /**
         * @var array<mixed> $data
         * @var string|false $result
         */
        $result = Xml::fromArray($data, $options)->saveXML();
        if ($result === false) {
            throw new SerializationFailureException(
                'XML serialization of View data failed.',
            );
        }

        return $result;
    }
}

View on GitHub (pinned to 1128eba9b0)