0

我正在创建一个 RESTful 网络服务,现在我正面临着新资源(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 数组?

4

1 回答 1

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 对象
(
    [季节] => 数组
        (
            [0] => SimpleXMLElement 对象
                (
                    [标题] => 新标题
                )

            [1] => SimpleXMLElement 对象
                (
                    [标题] => 新标题 2
                )

        )

)
大批
(
    [0] => 数组
        (
            [标题] => 新标题
        )

    [1] => 数组
        (
            [标题] => 新标题 2
        )

)
// 或者
大批
(
    [标题] => 数组
        (
            [0] => 新标题
            [1] => 新标题 2
        )

)
于 2013-01-25T01:08:52.613 回答