2013-01-24 36 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 
     ) 

)