簡體   English   中英

將XML字符串解析為PHP數組?

[英]Parse XML string as PHP Array?

我正在創建一個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 Array?

這對我有用,嘗試一下;

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

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM