2014-12-28 2 views
0

XML (데이터베이스)의 출력 레코드와 같은 단순한 (생각할 수있는) 것을 처리 할 수 ​​없습니다. 나는 웅변 모델이라는 고객을 가지고 있고 그래서 나는 응답 매크로 (http://www.laravel-tricks.com/tricks/responsexml-macro)를 설치하려고했습니다 DB를에서 출력하는 모든 고객을 보낼 내가 같이 호출 :Laravel XML로 db 레코드를 출력하는 방법은 무엇입니까?

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

을하지만 그때 나는 오류 "SimpleXMLElement있어 :: addChild() : 끝나지 않은 엔티티 참조 M ". 나는 또한 SimpleXMLELement를 사용하는 다른 솔루션을 시도해 보았습니다. 그래서 결과는 같았습니다.

+1

[laravel-tricks] (http://www.laravel-tricks.com/tricks/responsexml-macro#comment-1453496585)에 대한 의견을 읽어보십시오. 숫자 배열을 지원하는 수정 된 버전이 필요합니다. – lukasgeiter

+0

거의 완벽한 솔루션입니다. 나는 또한 거기에 설명되어있는 작은 코드를 변경했습니다 : http://stackoverflow.com/a/17028414/2487793 – Lukas

+2

당신은이 게시물의 미래 방문자에 대한 당신의 질문과 문서에 대한 대답을 제안합니다. – lukasgeiter

답변

0
<?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'); 
관련 문제