問題描述
無法使用 fopen/fwrite/fclose (php) 在 mysql 中保存 xml 文件內容 (Can't save xml file content in mysql with fopen/fwrite/fclose (php))
所以我正在使用 fopen/fwrite/fclose 在 php 中編寫一個 XML 文件,然後嘗試將該信息保存到 MySQL 數據庫 BLOB 字段中;但是,我遇到了一個問題,在將信息保存到 MySQL 之後,所有文件包含的是 "Resource id #33" 並且沒有我試圖保存的信息。
$blahXMLFile = fopen($_POST['scenBlahNewName'].".xml","wb");
fwrite($blahXMLFile, "<?xml version='1.0' encoding='UTF‑8' standalone='yes'?>");
fwrite($blahXMLFile, "<Blah>");
fwrite($blahXMLFile, "<Name>");
fwrite($blahXMLFile, $_POST['scenBlahNewName']);
fwrite($blahXMLFile, "</Name>");
fwrite($blahXMLFile, "</Blah>");
fclose($blahXMLFile);
$sql = "INSERT INTO blah (xmlFile)
VALUES ('$blahXMLFile');";
if($conn‑>query($sql) === TRUE) {
} else { echo "<script>alert('Error: " . $sql . "<br>" . $conn‑>error . "');</script>";
echo "Error: " . $sql . "<br>" . $conn‑>error;
} //end else
然後我使用 $blahXMLFile php 變量並嘗試將其保存在我的 MYSQL 數據庫的 BLOB 字段和“Resource id #33”是文件中的全部內容。如果我使用 javascript 來提醒 php 變量,情況也是如此。
我錯過了什麼?
編輯:根據評論嘗試在此處正確使用 fread:
$blahXMLResource = fopen($_POST['scenBlahNewName'].".xml","w");
$blahXMLFile = fread($blahXMLResource, filesize($_POST['scenBlahNewName'].".xml"));
因為這根本不再保存文件。
參考解法
方法 1:
Alright, so I got it; after advice from @chris85 I replaced my fopen/fwrite/fclose with file_put_contents (I was using file_get_contents, but that was appending rather than overwriting the files each time).
$blahXMLFile = $_POST['scenBlahNewName'].".xml";
$blahXMLFileContent = "<?xml version='1.0' encoding='UTF‑8' standalone='yes'?>
<Blah xmlns='uri:/mil/tatrc/physiology/datamodel' xmlns:xsi='http://www.w3.org/2001/XMLSchema‑instance' xsi:schemaLocation=''>
<Name>".$_POST['scenBlahNewName']."</Name>
</Blah>";
file_put_contents($blahXMLFile, $blahXMLFileContent);
echo "<script>alert('".addslashes($blahXMLFileContent)."');</script>";
$blahXMLFileContent is what I eventually put into the MySQL database.
(by Michael Anthony Leber、Michael Anthony Leber)