本文目录导读:

在 PHP 中“更新文档”通常指以下几种情况,我分别给出解决方案:
更新数据库中的文档/记录(最常见)
PDO 方式(推荐)
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
// 更新单条记录
$sql = "UPDATE users SET name = :name, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':name' => '新名字',
':email' => 'new@email.com',
':id' => 1
]);
echo "更新了 " . $stmt->rowCount() . " 条记录";
?>
MySQLi 方式
<?php
$conn = new mysqli('localhost', 'user', 'password', 'test');
$sql = "UPDATE users SET name = ?, email = ? WHERE id = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("ssi", $name, $email, $id);
$name = '新名字';
$email = 'new@email.com';
$id = 1;
$stmt->execute();
echo "更新了 " . $stmt->affected_rows . " 条记录";
?>
更新 Word/Excel 文档
更新 Word 文档(使用 PhpWord)
<?php
require_once 'vendor/autoload.php';
use PhpOffice\PhpWord\IOFactory;
$phpWord = IOFactory::load('document.docx');
$sections = $phpWord->getSections();
// 遍历段落进行修改
foreach ($sections as $section) {
foreach ($section->getElements() as $element) {
if (method_exists($element, 'getText')) {
$text = $element->getText();
// 替换文本内容
$element->setText(str_replace('旧文本', '新文本', $text));
}
}
}
// 保存修改
$writer = IOFactory::createWriter($phpWord, 'Word2007');
$writer->save('updated_document.docx');
?>
更新 PDF 文档
使用 TCPDF 添加内容
<?php
require_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8');
$pdf->SetCreator(PDF_CREATOR);
// 加载已有的PDF
$pdf->setSourceFile('original.pdf');
$tplIdx = $pdf->importPage(1);
$pdf->addPage();
$pdf->useTemplate($tplIdx);
// 在页面上添加文本
$pdf->SetFont('helvetica', 'B', 12);
$pdf->SetXY(50, 50);
$pdf->Write(5, '这是添加的新文本');
// 输出新的PDF
$pdf->Output('updated.pdf', 'F');
?>
更新 JSON 文档文件
<?php
// 读取JSON文件
$json = file_get_contents('data.json');
$data = json_decode($json, true);
// 修改数据
$data['name'] = '新的名称';
$data['age'] = 30;
// 写回文件
file_put_contents('data.json', json_encode($data, JSON_PRETTY_PRINT));
?>
更新 XML 文档
<?php
$xml = simplexml_load_file('data.xml');
// 修改节点值
$xml->user->name = '新名称';
$xml->user->age = 30;
// 保存修改
$xml->asXML('data.xml');
?>
使用 MongoDB 更新文档
<?php
$manager = new MongoDB\Driver\Manager('mongodb://localhost:27017');
// 更新单个文档
$bulk = new MongoDB\Driver\BulkWrite;
$bulk->update(
['name' => '旧名称'],
['$set' => ['name' => '新名称']]
);
$manager->executeBulkWrite('database.collection', $bulk);
// 批量更新
$filter = ['status' => 'inactive'];
$update = ['$set' => ['status' => 'active']];
$bulk->update($filter, $update, ['multi' => true]);
$manager->executeBulkWrite('database.collection', $bulk);
?>
选择建议
- 数据库记录更新:使用 PDO 或 MySQLi(最常用)
- Word/Excel 文件:使用 PhpSpreadsheet、PhpWord
- PDF 文件:使用 TCPDF、FPDF、mPDF
- PDF 编辑(高级):可以考虑使用 PDFlib 或 pdftk
- 配置文件:直接使用 file_put_contents 处理 JSON/YAML
需要根据你的具体需求选择合适的方案,最常用的是数据库更新,其次是对文件的操作。