2013-01-24 35 views
0

我正在創建一個RESTful webservice,現在我正面臨新資源的插入(Season資源)。這是POST請求的身體:將XML字符串解析爲PHP數組?

<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數組?

+0

'xml_parse_into_struct()' – clover

+0

爲什麼你有'緊湊型( 「請求」)''然後$ OBJ [ '請求']'? – nickb

回答

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 
     ) 

)