Skip to content
Advertisement

CodeIgniter – Process Simple XML & PHP

in the controller I have _send method. This method returns something like below:

 $xmlstr = <<<XML
<?xml version='1.0' standalone='yes' ?>
<status id="555555555" date="Wed, 28 Mar 2013 12:35:00 +0300">
<id>3806712345671174984921381</id>
<id>3806712345671174984921382</id>
<id>3806712345671174984921383</id>
<id>3806712345671174984921384</id>
<state error="Unknown1">Rejected1</state>
<state error="Unknown2">Rejected2</state>
<state error="">Accepted</state>
<state error="">Accepted</state>
</status>
XML;

This method called:

$req = $this->_send('bulk',$all_phones,$this->input->post('message'));

I am unable to create array or object suitable for passing to model for inserting into DB. Below what I have now.

$xml = new SimpleXMLElement($xmlstr);


foreach ($xml as $child) {

                if ($child->getName() == 'id') {
                    $id[] = $child->id;
                }

                if ($child->getName() == 'state') {
                    $state[] = $child;
                    //$state[] = $child['error'];
                }

}

return array_merge($id,$state);

I am attempting to achieve something like this array:

array(0 => array(
                 'id' => '3806712345671174984921381',
                 'state' => 'Rejected1',
                 'state_error' => 'Unknown1'),
      1 => array( ....

Problem with error attribute with fault array_merge.

Any ideas?

Advertisement

Answer

This is how you could do it:

// Load XML
$xmlstr = '<?xml version="1.0" standalone="yes" ?>
<status id="555555555" date="Wed, 28 Mar 2013 12:35:00 +0300">
<id>3806712345671174984921381</id>
<id>3806712345671174984921382</id>
<id>3806712345671174984921383</id>
<id>3806712345671174984921384</id>
<state error="Unknown1">Rejected1</state>
<state error="Unknown2">Rejected2</state>
<state error="">Accepted</state>
<state error="">Accepted</state>
</status>';
$xml = new SimpleXMLElement($xmlstr);

// Init
$parsed_data = array();

// Parse Id
foreach ($xml->id as $id)
{
    $parsed_data[] = array(
        'id' => (string)$id,
        'state' => '',
        'state_error' => ''
    );
}

// Parse State & State Error
$i = 0;
foreach ($xml->state as $state)
{
    $parsed_data[$i]['state'] = (string)$state;
    $parsed_data[$i]['state_error'] = (string)$state['error'];
    $i++;
}

// Output
var_dump($parsed_data);

Here’s the output I got:

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement