Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm creating a RESTful webservice, right now I'm facing the insertion of the new resource (the Season resource). This is the body of the POST request:

<request>
   <Season>
      <title>new title</title>
   </Season>
</request>

and this is the controller that effectively perform the insertion:

public function add() {
    // i feel shame for this line
    $request = json_decode(json_encode((array) simplexml_load_string($this->request->input())), 1);

    if (!empty($request)) {
        $obj = compact("request");
        if ($this->Season->save($obj['request'])) {
            $output['status'] = Configure::read('WS_SUCCESS');
            $output['message'] = 'OK';
        } else {
            $output['status'] = Configure::read('WS_GENERIC_ERROR');
            $output['message'] = 'KO';
        }
        $this->set('output', $output);
    }
    $this->render('generic_response');
}

The code works pretty well, but as I wrote in the snippet above I consider the first line of the controller really ugly, so, the question is: How can I parse XML string as PHP Array?

share|improve this question
    
xml_parse_into_struct() –  clover Jan 24 '13 at 23:43
    
Why do you have compact("request") then $obj['request']?? –  nickb Jan 24 '13 at 23:44

1 Answer 1

up vote 1 down vote accepted

This worked for me, try it;

<request>
   <Season>
      <title>new title</title>
   </Season>
   <Season>
      <title>new title 2</title>
   </Season>
</request>

.

$xml = simplexml_load_file("xml.xml");
// print_r($xml);
$xml_array = array();
foreach ($xml as $x) {
    $xml_array[]['title'] = (string) $x->title;
    // or 
    // $xml_array['title'][] = (string) $x->title;
}
print_r($xml_array);

Result;

SimpleXMLElement Object
(
    [Season] => Array
        (
            [0] => SimpleXMLElement Object
                (
                    [title] => new title
                )

            [1] => SimpleXMLElement Object
                (
                    [title] => new title 2
                )

        )

)
Array
(
    [0] => Array
        (
            [title] => new title
        )

    [1] => Array
        (
            [title] => new title 2
        )

)
// or
Array
(
    [title] => Array
        (
            [0] => new title
            [1] => new title 2
        )

)
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.