I am trying to figure out how to send a response consisting of this XML structure, using PHP with MySQL.
I’m creating the response using echo "<?xml version...";
but I’m trying to do it with SimpleXML object.
Query Objects:
$data_workers
-> $data_workers["id"]; $data_workers["name"];
$data_works
->$data_works["worker_id"]; $data_works["id"]; $data_works["date"];
Code:
<?xml version="1.0"?>
<response status="1" status_description="">
<worker id="1" name="John Smith" phone="1956456456" >
<works>
<work id="1" date="01-01-2023" total="350" />
<work id="2" date="02-01-2023" total="350" />
</works>
<tools>
<tool type="Hammer" color="red"/>
<tool type="Tape" color="blue"/>
</tools>
<pendings/>
</worker>
</response>
Can somebody tell me if this is possible to do with PHP handling like json responses?
2
Answers
Your can try following code
Generic conversion from an object/data structure to XML is complex. You would need additional information about the nesting and what goes into an attribute or text content. Here are JSON based formats what include all information for XML like JSONML (JSON Markup Language). Other concepts use class/interface definitions for the model with annotations.
The other way is to use DOM or XMLWriter to generate a specific XML output. SimpleXML is an abstraction an will only work for some (basic) formats.
In DOM you use methods on the document to create different node types (elements, text nodes, attribute, comments, …), then the methods of the parent node to append/insert the node. If you create a document from scratch you will only need
appendChild()
(or the newappend()
in PHP 8). Methods on the created node are used modify it (add attributes, child nodes, …).Here is an example with the data you provided:
Output: