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

コードは非常にうまく機能しますが、上記のスニペットで書いたように、コントローラーの最初の行が非常に見にくいと考えています。

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 に答える