2010-12-01 147 views
0

我需要從我的php代碼創建xml文件的幫助。我創建了一個函數,它根據需要形成xml,但我不知道如何將文件中形成的xml保存。從php創建xml文件的問題

此外,如果你還可以告訴我,下次如何更新已經創建的XML文件。

我的代碼看起來像下面:

public function create_xml() 
{ 
    $output = "<?xml version=\"1.0\" encoding=\"utf-8\" ?> "; 
    $output .= "<data>"; 
    $output .= "<news>"; 
    $news_articles = new C7_News(); 
    $db = C7_Bootstrap::getDb(); 
    $foxsport_sql = "SELECT headline, link FROM c7_news 
         WHERE source = 'foxsports' AND category = 'Breaking News' 
         LIMIT 0,4"; 
    $foxsport_rowset = $db->fetchAll($foxsport_sql); 
    $data = array(); 
    foreach($foxsport_rowset as $foxsport_row) 
    { 
     $output .= "<title>"; 
     $output .= "<description>"; 
     $output .= "<![CDATA["; 
     $output .= $foxsport_row['headline']; 
     $output .= "]]>"; 
     $output .= "<link>"; 
     $output .= $foxsport_row['link']; 
     $output .= "</link>"; 
     $output .= "</title>"; 
    } 
    $output .= "</news>"; 
    $output .= "</data>"; 

} 

我可能會做錯事太多,PLZ讓我知道創建XML的最好方法。

謝謝 Zeeshan

回答

2

我會在這裏添加更多信息。

此外,如果你還可以告訴我,下次如何更新已經創建的XML文件。

如果要在解析XML 更新,在SimpleXml extension提供易用的API 解析寫作XML文件。

我也可能做錯了,請讓我知道創建XML的最佳方式。

有很多方法可以做到這一點,但我更喜歡使用PHP 「模板引擎」寫HTML時XML(或任何* ML這個問題)。

<?php echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?> " ?> 
    <?php 
     $news_articles = new C7_News(); 
     $db = C7_Bootstrap::getDb(); 
     $foxsport_sql = "SELECT headline, link FROM c7_news 
        WHERE source = 'foxsports' AND category = 'Breaking News' 
        LIMIT 0,4"; 
     $foxsport_rowset = $db->fetchAll($foxsport_sql); 
    ?> 
    <data> 
     <news> 
     <?php foreach($foxsport_rowset as $foxsport_row): 
     <title> 
      <description> 
      <![CDATA[ 
      <?php echo $foxsport_row['headline'] ?> 
      ]]> 
      </description> 
      <link><?php echo $foxsport_row['link']</link> 
     </title> 
     <?php endforeach; ?> 
     </news> 
    </data> 

這將輸出的XML 是一個更容易閱讀

但我不知道如何保存的XML文件中的。

至於如何將這些保存到一個文件,你應該有另一個PHP文件include這個「模板」(假設該模板被稱爲xml_template.php):

ob_start(); 
    include dirname(__FILE__) . DIRECTORY_SEPARATOR . 'xml_template.php'; 
    $output = ob_get_clean(); 

然後你再有XML字符串上的$output變量,可以做的弗拉德注意到。P

// If file is missing, it will create it. 
    $file = fopen("file.xml", "w"); 
    fwrite($file, $output); 
    fclose($file); 
0

在你的函數的末尾添加這一點。

// If file is missing, it will create it. 
$file = fopen("file.xml", "w"); 
fwrite($file, $output); 
fclose($file); 
0

使用

file_put_contents($file, $output); 

你可能想在參數傳遞的文件的路徑:

$stream->create_xml($file); 

或原因,應該通過其他方法來處理/類,例如

$stream->create_xml(); 
$stream->save_xml($file);