skip to Main Content

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


  1. Your can try following code

     $data = ['name' => 'test','email' => '[email protected]'];// change this with your array
     $xml = new SimpleXMLElement('<root/>');
     array_walk_recursive($data, array($xml, 'addChild'));
     echo $xml->asXML();
    
    Login or Signup to reply.
  2. 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 new append() 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:

    $data_workers = [
         ['id'=>"1", 'name'=>"John Smith", 'phone'=>"1956456456"],
         ['id'=>"2", 'name'=>"Jane Doe", 'phone'=>"1956456457"]
    ];
    
    $data_works = [
         ['id'=>"1", 'worker_id'=>"1", 'date'=>"01-01-2023", 'total'=>"350"],
         ['id'=>"2", 'worker_id'=>"1", 'date'=>"01-01-2023", 'total'=>"360"],
         ['id'=>"3", 'worker_id'=>"2", 'date'=>"01-01-2023", 'total'=>"370"]
    ];
    
    $document = new DOMDocument();
    // create and append the document element "response"
    $document->appendChild(
        $response = $document->createElement('response')
    );
    // add attributes to it
    $response->setAttribute('status', "1");
    $response->setAttribute('status_description', '');
    
    // iterate the worker data
    foreach ($data_workers as $workerData) {
        // create "worker" element and append to "response"
        $response->appendChild(
            $worker = $document->createElement('worker')
        );
        $worker->setAttribute('id', $workerData['id']);
        $worker->setAttribute('name', $workerData['name']);
        $worker->setAttribute('phone', $workerData['phone']);
        
        // filter works by worker_id 
        $worksOfWorker = array_filter(
            $data_works, 
            fn($current) => $current['worker_id'] === $workerData['id']
        );
         
        $worker->appendChild(
            $works = $document->createElement('works')
        );
        
        foreach ($worksOfWorker as $workData) {
            $works->appendChild(
                $work = $document->createElement('work')
            );
            $work->setAttribute('id', $workData['id']);
            $work->setAttribute('date', $workData['date']);
            $work->setAttribute('total', $workData['total']);
        }
        
    }
    
    $document->formatOutput = true;
    echo $document->saveXML();
    

    Output:

    <?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="01-01-2023" total="360"/>
        </works>
      </worker>
      <worker id="2" name="Jane Doe" phone="1956456457">
        <works>
          <work id="3" date="01-01-2023" total="370"/>
        </works>
      </worker>
    </response>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search