您好,登錄后才能下訂單哦!
laravel中怎么輸出xml數據,相信很多沒有經驗的人對此束手無策,為此本文總結了問題出現的原因和解決方法,通過這篇文章希望你能解決這個問題。
laravel框架怎么返回xml格式數據?
如果用header(“Content-type: text/xml”);
這樣的話是沒有效果的,會提示這樣的錯誤:
This page contains the following errors:
error on line 14 at column 6: XML declaration allowed only at the start of the document
Below is a rendering of the page up to the first error.
laravel框架在輸出xml的時候會自行用text/html方式返回數據,解決辦法:
需要return response($xml,200)->header(“Content-type”,“text/xml”);這樣的方式才能改變header頭
laravel返回xml數據格式例子:
/** * 神馬搜索數據結構化,written:yangxingyi Data:2018-10-25 11:15 */ public function index(Request $request){ $data_array = array( array( 'title' => 'title1', 'content' => 'content1', 'pubdate' => '2009-10-11', ), array( 'title' => 'title2', 'content' => 'content2', 'pubdate' => '2009-11-11', ) ); $title_size = 1; $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; $xml .= "<article>\n"; foreach ($data_array as $data) { $xml .= $this->create_item($data['title'], $title_size, $data['content'], $data['pubdate']); } $xml .= "</article>\n"; #echo $xml; return response($xml,200)->header("Content-type","text/xml"); } /** * 神馬搜索數據結構化,節點的具體內容 written:yangxingyi */ private function create_item($title_data, $title_size, $content_data, $pubdate_data) { $item = "<item>\n"; $item .= "<title size=\"" . $title_size . "\">" . $title_data . "</title>\n"; $item .= "<content>" . $content_data . "</content>\n"; $item .= " <pubdate>" . $pubdate_data . "</pubdate>\n"; $item .= "</item>\n"; return $item; }
PHP生成xml格式的數據直接加上 header(“Content-type: text/xml”);頭就行了
<?php header("Content-type: text/xml"); $data_array = array( array( 'title' => 'title1', 'content' => 'content1', 'pubdate' => '2009-10-11', ), array( 'title' => 'title2', 'content' => 'content2', 'pubdate' => '2009-11-11', ) ); $title_size = 1; $xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"; $xml .= "<article>\n"; foreach ($data_array as $data) { $xml .= create_item($data['title'], $title_size, $data['content'], $data['pubdate']); } $xml .= "</article>\n"; echo $xml; //創建XML單項 function create_item($title_data, $title_size, $content_data, $pubdate_data) { $item = "<item>\n"; $item .= "<title size=\"" . $title_size . "\">" . $title_data . "</title>\n"; $item .= "<content>" . $content_data . "</content>\n"; $item .= " <pubdate>" . $pubdate_data . "</pubdate>\n"; $item .= "</item>\n"; return $item; } ?>
看完上述內容,你們掌握laravel中怎么輸出xml數據的方法了嗎?如果還想學到更多技能或想了解更多相關內容,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。