2017-06-03 129 views
0

我正在使用php進行搜索功能,我需要將</pages>添加到我正在寫入的文件末尾。 </pages>最後只能寫一次。Php一次寫入代碼行

$target_dir = "uploads/"; 
$target_file = $target_dir . basename($_FILES["fileToUpload"] 
["name"]); 
$uploadOk = 1; 
$imageFileType = pathinfo($target_file,PATHINFO_EXTENSION); 
// Check if image file is a actual image or fake image 

// Check if file already exists 
if (file_exists($target_file)) { 
echo "ERR: 418 (File all ready exists)\n"; 
$uploadOk = 0; 
} 
// Check file size 
if ($_FILES["fileToUpload"]["size"] > 500000) { 
echo "ERR: 418 (File too large)\n"; 
$uploadOk = 0; 
} 
// Allow certain file formats 
if($imageFileType != "txt") { 
echo "ERR: 418 (Supported file types - .txt)\n"; 
$uploadOk = 0; 
} 
// Check if $uploadOk is set to 0 by an error 
if ($uploadOk == 0) { 
echo "Sorry, your file was not uploaded."; 
// if everything is ok, try to upload file 
} else { 
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"],     
$target_file)) { 
    echo "The file ". basename($_FILES["fileToUpload"]["name"]). "  
has been uploaded."; 
} else { 
    echo "Sorry, there was an error uploading your file."; 
} 
} 

$contentsbro = file_get_contents("links.xml"); 
$myfile = fopen("links.xml", "w") or die("Unable to open file!"); 
$txt = "<link><title>". basename($_FILES["fileToUpload"]["name"]). " 
</title> 
<url>https://fidead.000webhostapp.com/uploads/". basename( 
$_FILES["fileToUpload"]["name"]). "</url> 
</link>"; 
$txto = $contentsbro . $txt; 
fwrite($myfile, $txto); 
fclose($myfile); 

?> 

我需要知道如何在最後寫一次字符串,否則會給我一個錯誤。

回答

0

想必你有這樣的事情(有更多的條目):

<?xml version="1.0" encoding="UTF-8" ?> 
<pages> 
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url> 
</pages> 

你或許應該使用XML解析器正確地做到這一點:

# Loads the content of the file 
$XML = simplexml_load_file('links.xml'); 
# Adds to the URL array 
$XML->addChild('url','https://fidead.000webhostapp.com/uploads/newfile.jpg'); 
# Saves the file back 
file_put_contents('links.xml',$XML->asXml()); 

爲您提供:

<?xml version="1.0" encoding="UTF-8"?> 
<pages> 
    <url>https://fidead.000webhostapp.com/uploads/filename.jpg</url> 
<url>https://fidead.000webhostapp.com/uploads/newfile.jpg</url></pages> 

編輯:

相反的:

$contentsbro = file_get_contents("links.xml"); 
$myfile = fopen("links.xml", "w") or die("Unable to open file!"); 
etc.... 

你應該嘗試:

# Loads the content of the file 
$XML = simplexml_load_file('links.xml'); 
# Make a new link child 
$link = $XML->addChild('link'); 
# Create a new child under the link for title 
$link->addChild('title',basename($_FILES["fileToUpload"]["name"])); 
# Create a new child under the link for url 
$link->addChild('url','https://fidead.000webhostapp.com/uploads/'.basename($_FILES["fileToUpload"]["name"])); 
# Saves the file back 
file_put_contents('links.xml',$XML->asXml()); 
+0

我還不是很瞭解PHP所以你能告訴我完成的代碼 – GoGode

+0

也有鏈接 – GoGode

+0

所以它上面的標題看起來像這樣'名稱 https://fidead.000webhostapp.com/uploads/filename.jpg ' – GoGode