背景:
seo的同事要批量提交xml格式的資料到搜尋引擎,目前專案用laravel框架開發的,所以就有了這篇文章的誕生了。網路上有不少關於php輸出xml格式的例子,小弟不才也搬過,只是在php檔案上面測試是沒問題的,把它搬到laravel框架裡面,就有有坑了,主要原因是header頭的問題。
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; } ?>
更多PHP相關知識,請造訪PHP教學!
以上是laravel輸出xml數據,php輸出xml格式數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!