如何在Laravel 5中将数据从mysql存储到XML? [英] How can i store data from mysql to XML in Laravel 5?

查看:80
本文介绍了如何在Laravel 5中将数据从mysql存储到XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将数据从MySQL提取到XML并在Laravel 5中回显它.

I need data fetching from MySQL to XML and echo it in Laravel 5.

这是我传统上的做法:

    $query = "SELECT * FROM table";
    $result = mysql_query($query);

    $dom = new DOMDocument("1.0");
    $parnode = $dom->appendChild($node);

    while ($row = @mysql_fetch_assoc($result)){

    $node = $dom->createElement("data");
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("username",$row['username']);
    $newnode->setAttribute("login_attemp", $row['login_attemp']);
    $newnode->setAttribute("mobile", $row['mobile']);
    $newnode->setAttribute("email", $row['email']);
    $newnode->setAttribute("type", $row['type']);
    }

    echo $dom->saveXML();

现在,我希望在Laravel 5中完成同样的操作,请帮助我

Now, i want the same to be done in Laravel 5, Please help me

预先感谢

推荐答案

从您的问题来看,似乎还不清楚是什么问题.

From your question it's not quite clear what seems to be the problem.

您使用模型来获取数据,然后像以前一样通过使用DOMDocument或将其更好地与XMLWriter结合使用,将其转换为xml.

You use the model to grab the data and then you turn it into xml like you've done before by using DOMDocument or probably better with XMLWriter i.e.

use Illuminate\Support\Facades\Response;
use App\User;

Route::get('/users/xml', function() {
    $users = User::all();

    $xml = new XMLWriter();
    $xml->openMemory();
    $xml->startDocument();
    $xml->startElement('users');
    foreach($users as $user) {
        $xml->startElement('data');
        $xml->writeAttribute('id', $user->id);
        $xml->writeAttribute('firstname', $user->firstname);
        $xml->writeAttribute('lastname', $user->lastname);
        $xml->writeAttribute('email', $user->email);
        $xml->endElement();
    }
    $xml->endElement();
    $xml->endDocument();

    $content = $xml->outputMemory();
    $xml = null;

    return response($content)->header('Content-Type', 'text/xml');
});

示例输出:

<?xml version="1.0"?>
<users>
  <data id="1" firstname="John" lastname="Doe" email="john@example.com"/>
  <data id="2" firstname="Mark" lastname="Lee" email="mark@example.com"/>
  <data id="3" firstname="Jane" lastname="Doe" email="jane@example.com"/>
</users>

这篇关于如何在Laravel 5中将数据从mysql存储到XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆