2017-07-18 83 views
0

我正在嘗試從網站獲取xml文件並將其放入本地空xml文件(myxml.xml)中。我的代碼是返回一個空文件。PHP將文件內容從url寫入本地文件

我們的目標是從http://website.com/theirxml.xml中獲取xml文件內容並將其放入myxml.xml

要注意,我這樣做的唯一原因是因爲我的主機網站上的xml格式不正確,所以我需要在我自己的本地版本上更改它。因此,我需要的是從文件中獲取字符串。

<?php 
$myfile = fopen("myxml.xml", "w") or die("Unable to open file!"); 
$ch = curl_init(); 
curl_setopt($ch, CURLOPT_URL, "http://website.com/theirxml.xml"); 
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
$output = curl_exec($ch); 
fwrite($myfile, $output); 
fclose($myfile); 
?> 
+1

而你的問題是? –

+0

我沒有得到任何迴應,也沒有錯誤陳述。 –

+1

無論你的方式或@ colbuton的方式(我更喜歡)使用'error_reporting(E_ALL); ini_set('display_errors','1');' – AbraCadaver

回答

4

很簡單:

file_put_contents('myxml.xml', file_get_contents('http://website.com/theirxml.xml'); 

THX到陳以桐爲這個技巧:你需要在你的php.ini激活allow_url_fopen

+0

你的方式唯一的問題是,我得到一個'拒絕連接'錯誤。 –

+0

@JasonChen你檢查了你的phpinfo以確保'allow_url_fopen'被啓用? – Trojan404

1

您可以使用「simplexml_load_file」函數從XML中獲取數據。

$url="http://website.com/theirxml.xml"; 
$xml = simplexml_load_file($url); 
file_put_contents('myxml.xml',$xml);