栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > PHP

laravel输出xml数据,php输出xml格式数据

PHP 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

laravel输出xml数据,php输出xml格式数据

背景:

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数据格式例子:

 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");
    }
 
    private function create_item($title_data, $title_size, $content_data, $pubdate_data)
    {
 $item = "n";
 $item .= "" . $title_data . "n";
 $item .= "" . $content_data . "n";
 $item .= " " . $pubdate_data . "n";
 $item .= "n";
 return $item;
    }

PHP生成xml格式的数据直接加上 header(“Content-type: text/xml”);头就行了

 '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 .= "" . $title_data . "n";
    $item .= "" . $content_data . "n";
    $item .= " " . $pubdate_data . "n";
    $item .= "n";
    return $item;
}
?>

更多PHP相关知识,请访问PHP教程!

以上就是laravel输出xml数据,php输出xml格式数据的详细内容,更多请关注考高分网其它相关文章!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/263352.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号