laravel输出xml数据,php输出xml格式数据-php教程

资源魔 30 0
布景:

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 php开发教程 php开发资料 php开发自学 Laravel

抱歉,评论功能暂时关闭!