将XML字符串解析为PHP数组?

时间:2013-01-24 23:38:47

标签: php arrays cakephp-2.0

我正在创建一个RESTful Web服务,现在我正面临着插入新资源(Season资源)。这是POST请求的主体:

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

这是有效执行插入的控制器:

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');
}

代码工作得很好,但正如我在上面的代码片段中所写,我认为控制器的第一行真的很难看,所以,问题是:如何将XML字符串解析为PHP数组?

1 个答案:

答案 0 :(得分:1)

这对我有用,试试吧;

<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);

结果;

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
        )

)