I have an array that needs to be serialized to either JSON or XML depending on the requested content type.
$responseArray = [
"name" => ""
, "status" => -1
, "message" => "An unknown error has occurred."
];
Encoding it with JSON works just fine
$plainTextResponse = $serializer->serialize($responseArray, 'json');
{"name":"","status":-1,"message":"An unknown error has occurred."}
Which is right and exactly what I need. The problem is representing it as XML
$plainTextResponse = $serializer->serialize($responseArray, 'xml');
<?xml version="1.0"?>
<response>
<name></name>
<status>-1</status>
<message>An unknown error has occurred.</message>
</response>
But intead of nesting those properties under command I need them to appear as attributes. That is doable this way (notice the @ before attribute names)
$responseArray = [
"@name" => ""
, "@status" => -1
, "@message" => "An unknown error has occurred."
];
...
$plainTextResponse = $serializer->serialize($responseArray, 'xml');
<?xml version="1.0"?>
<response name="" status="-1" message="An unknown error has occurred."/>
And obviously if I try to convert that to JSON then it will leave those @ in the names of the attributes
$plainTextResponse = $serializer->serialize($responseArray, 'json');
{"@name":"","@status":-1,"@message":"An unknown error has occurred."}
Is there a way to serialise an array so that it adds attributes in XML and does not have @ in json?