m.faizul
m.faizul

Reputation: 1

Convert MySQL result to XML format using PHP with multidimensional array

I am trying to get my XML format be like this:

xml format I want

but my code now does not loop for the 'order_line' array and will return like this:

false XML format

below are sample of my code I did:

$result = $this->db->query("SELECT * FROM `grn_order` a");

    foreach($result->result() as $row )
    {
        $result_line = $this->db->query("SELECT * FROM `grn_order_line` a where a.order_no = '$row->order_no'");
        foreach($result_line->result() as $row_line);
        {
            $line = array(
                'guid' => $row_line->guid,
                'itemcode' => $row_line->itemcode,
            );
        }

        $my_array[] = array(
            'order_no' => $row->order_no,
            'loc_code' => $row->loc_code,
            'trans_code' => $row->trans_code,
            'po_no' => $row->po_no,
            'order_line' => $line
        );
    } $xml = new SimpleXMLElement('<orders/>');

    // function callback
    $data = $this->array2XML($xml, $my_array);
    print $xml->asXML();

function array2XML($obj, $array)
{
    foreach ($array as $key => $value)
    {
        if(is_numeric($key))

        $key = 'order';

        if (is_array($value))
        {
            $node = $obj->addChild($key);
            $this->array2XML($node, $value);
        }
        else
        {
            $obj->addChild($key, htmlspecialchars($value));
        }
    }
}

Upvotes: 0

Views: 273

Answers (1)

Nigel Ren
Nigel Ren

Reputation: 57131

You keep on overwriting the last line in your load loop. Change it to...

$line = [];
foreach($result_line->result() as $row_line);
{
    $line[] = array(
        'guid' => $row_line->guid,
        'itemcode' => $row_line->itemcode,
    );
}

So each line is added using $line[].

Upvotes: 1

Related Questions