Home>Article>Backend Development> laravel outputs xml data, php outputs xml format data
Background:
A colleague from seo needs to submit data in xml format to the search engine in batches. The current project is developed using the laravel framework, so this article was born. There are many examples on the Internet about PHP outputting XML format. I have also moved it before. It is no problem to just test it on the PHP file. If I move it to the Laravel framework, there will be pitfalls. The main reason is the header header. question.
How does the laravel framework return xml format data?
If you use header(“Content-type: text/xml”);
this will have no effect and an error like this will be prompted:
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.
The laravel framework will return data in text/html mode when outputting xml. Solution:
requires return response($xml,200)->header ("Content-type", "text/xml"); This way can change the header header
laravel returns xml data format example:
/** * 神马搜索数据结构化,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 = "\n"; $xml .= "\n"; foreach ($data_array as $data) { $xml .= $this->create_item($data['title'], $title_size, $data['content'], $data['pubdate']); } $xml .= " \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 = "- \n"; $item .= "
\n"; return $item; }" . $title_data . " \n"; $item .= "" . $content_data . " \n"; $item .= "" . $pubdate_data . " \n"; $item .= "
PHP generates data in xml format and adds header("Content-type: text/xml"); header.
'title1', 'content' => 'content1', 'pubdate' => '2009-10-11', ), array( 'title' => 'title2', 'content' => 'content2', 'pubdate' => '2009-11-11', ) ); $title_size = 1; $xml = "\n"; $xml .= "\n"; foreach ($data_array as $data) { $xml .= create_item($data['title'], $title_size, $data['content'], $data['pubdate']); } $xml .= " \n"; echo $xml; //创建XML单项 function create_item($title_data, $title_size, $content_data, $pubdate_data) { $item = "- \n"; $item .= "
\n"; return $item; } ?>" . $title_data . " \n"; $item .= "" . $content_data . " \n"; $item .= "" . $pubdate_data . " \n"; $item .= "
For more PHP related knowledge, please visitPHP tutorial!
The above is the detailed content of laravel outputs xml data, php outputs xml format data. For more information, please follow other related articles on the PHP Chinese website!