2016-06-14 83 views
1

我正在用laravel 4構建項目。我正試圖將MySQL數據導出到XML文檔。我設法保存一個.xml文件,但是裏面沒有數據,或者當我添加 - > get()方法到$ sales時,彈出錯誤。如何使用laravel將mysql表導出到xml文件

如何將數據庫中選定的數據導出到xml文件?我的目標是創造這樣的事情:image

$sales = Sale::where('Status', '=', 'ON') 
     ->orderBy('updated_at', 'asc'); //->get() here brings an error. 

    try 
    { 

     $xml = new XMLWriter(); 

     $xml->openURI('documents/mailouts/example.xml'); 

     $xml->startDocument('1.0'); 

     $xml->startElement('sales'); 

     foreach ($sales as $sale) { 


      $xml->startElement('sale'); 

      $xml->startElement('REF', $sale->SaleID); 
      $xml->endElement(); 

      $xml->startElement('COUNTY', $sale->county); 
      $xml->endElement(); 

      $xml->startElement('BOP1', $sale->SaleBop1); 
      $xml->endElement(); 

      $xml->startElement('OFFICE', $sale->SaleOffice); 
      $xml->endElement(); 

      $xml->endElement(); 
     } 

     $xml->endElement(); 
     $xml->endDocument(); 

     $xml->flush(); 

     Session::flash('success', 'success.'); 
    } 
    catch(Exception $e) 
    { 
     Session::flash('error','problem'); 
    } 


    return Redirect::route('sendouts.generate'); 

回答

0

解決它!

而不是開始寫入元素的新元素。我錯誤的用法錯誤。

$sales = Sale::where('Status', '=', 'ON') 
    ->orderBy('updated_at', 'asc'); //->get() here brings an error. 

try 
{ 

    $xml = new XMLWriter(); 

    $xml->openURI('documents/mailouts/example.xml'); 

    $xml->startDocument('1.0'); 

    $xml->startElement('sales'); 

    foreach ($sales as $sale) { 


     $xml->startElement('sale'); 

     $xml->writeElement('REF', $sale->SaleID); 
     $xml->writeElement('COUNTY', $sale->county); 
     $xml->writeElement('BOP1', $sale->SaleBop1); 
     $xml->writeElement('OFFICE', $sale->SaleOffice); 


     $xml->endElement(); 
    } 

    $xml->endElement(); 
    $xml->endDocument(); 

    $xml->flush(); 

    Session::flash('success', 'success.'); 
} 
catch(Exception $e) 
{ 
    Session::flash('error','problem'); 
} 


return Redirect::route('sendouts.generate');