Laravel 如何将数据库记录输出为 XML?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27676828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:36:27  来源:igfitidea点击:

Laravel how to output db records as XML?

phpxmlapilaravel

提问by Lukas

I cant deal with such simple (I think) thing like output records from database as XML. I have eloquent model named Customer and I want to send to output all customers from db so I've tried to install response macro ( http://www.laravel-tricks.com/tricks/responsexml-macro) and I call it like this:

我无法处理像 XML 那样从数据库输出记录这样简单(我认为)的事情。我有一个名为 Customer 的雄辩模型,我想从 db 发送输出所有客户,所以我尝试安装响应宏(http://www.laravel-tricks.com/tricks/responsexml-macro),我称之为这个:

public function showCustomers()
{
   $customers = Customer::all()->toArray();
   return Response::xml($customers);
}

but then I got error "SimpleXMLElement::addChild(): unterminated entity reference M" . I tried also other solution which used SimpleXMLELement also so the result was the same.

但后来我收到错误 "SimpleXMLElement::addChild(): unterminated entity reference M" 。我还尝试了其他使用 SimpleXMLELement 的解决方案,所以结果是一样的。

回答by Mark

Try this package:

试试这个包:

https://github.com/mtownsend5512/response-xml

https://github.com/mtownsend5512/response-xml

Then it's as easy as

然后就这么简单

$customers = Customer::all();
return response()->xml($customers);

回答by Vaha

https://github.com/dwightwatson/sitemap- very useful utility, works with Laravel 4.*, 5.*.

https://github.com/dwightwatson/sitemap- 非常有用的实用程序,适用于Laravel 4.*, 5.*

Install:

安装:

composer require watson/sitemap

composer require watson/sitemap

Add the service provider to your config/app.php file.

将服务提供者添加到您的 config/app.php 文件中。

Watson\Sitemap\SitemapServiceProvider::class

Add the alias to the facade, also in config/app.php.

将别名添加到外观,也在 config/app.php 中。

'Sitemap' => Watson\Sitemap\Facades\Sitemap::class

Usage example:

用法示例:

namespace App\Http\Controllers;

use App\Models\Categories;
use App\Models\Essays;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
use Watson\Sitemap\Sitemap;

/**
 * Class SitemapController, generates and shows xml sitemap
 *
 * @package App\Http\Controllers
 */
class SitemapController
{
    public function index() {
        // init sitemap obj
        $sitemap = new Sitemap(
            Cache::store('file'),
            new Request()
        );

        $essayModel = new Essays();
        $categoryModel = new Categories();

        $categoriesArr = $categoryModel->getAllPublishedCategories();

        // add to sitemap all the categories
        foreach ($categoriesArr as $categoryRes) {
            $sitemap->addTag(
                url(
                    "/" . config('custom.urlBases.essaysCategory')
                    . "/" . Str::slug($categoryRes->name, "-") . "-{$categoryRes->id}"
                ),
                $categoryRes->cat_publication_time,
                'daily',
                '0.5'
            );
        }

        $essaysArr = $essayModel->getAllEssays();

        // add to sitemap all the essays
        foreach ($essaysArr as $essay) {
            $sitemap->addTag(
                url(config('custom.urlBases.essayPage') . '/' . $essay->url . '-' . $essay->id),
                $essay->publication_time,
                'daily',
                '0.5'
            );
        }

        return $sitemap->render();
    }
}

Returns content like next:

返回内容如下:

<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
    <loc>page-url-here</loc>
    <lastmod>2017-02-08T19:52:37+00:00</lastmod>
    <changefreq>daily</changefreq>
    <priority>0.5</priority>
</url>

回答by Ley

<?php
// macros.php
Response::macro('xml', function(array $vars, $status = 200, array $header = [], $xml = null)
{
    if (is_null($xml)) {
        $xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><response/>');
    }
    foreach ($vars as $key => $value) {
        if (is_array($value)) {
            Response::xml($value, $status, $header, $xml->addChild($key));
        } else {
            $xml->addChild($key, $value);
        }
    }
    if (empty($header)) {
        $header['Content-Type'] = 'application/xml';
    }
    return Response::make($xml->asXML(), $status, $header);
});
?>

<?php
// app/start/global.php
// add require macros.php
require app_path() . '/macros.php';
?>

<?php
// How to use
// routes.php
Route::get('api.{ext}', function()
{
    $data = ['status' => 'OK'];
    $ext = File::extension(Request::url());
    return Response::$ext($data);
})->where('ext', 'xml|json');