萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 與 AJAX 整合 XML 應用開發實戰

背景與架構

在 SOA 架構下,XML 作為跨平台資料交換標準,搭配 PHP 後端與 AJAX 前端,可構建輕量級的企業級應用。本文以「客戶資料管理」為例,示範完整流程。

資料庫與 XML Schema 設計

<!-- customers.xsd -->
<xs:schema xmlns:xs="https://www.w3.org/2001/XMLSchema">
  <xs:element name="customers">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="customer" maxOccurs="unbounded">
          <xs:complexType>
            <xs:sequence>
              <xs:element name="id" type="xs:integer"/>
              <xs:element name="name" type="xs:string"/>
              <xs:element name="email" type="xs:string"/>
              <xs:element name="phone" type="xs:string" minOccurs="0"/>
            </xs:sequence>
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

後端 PHP Web Service (XML-RPC 風格)

<?php
// api/customers.php
header('Content-Type: application/xml; charset=utf-8');
require_once 'db.php'; // PDO 連線

$action = $_GET['action'] ?? 'list';
$xml = new DOMDocument('1.0', 'utf-8');
$xml->formatOutput = true;
$root = $xml->createElement('customers');
$xml->appendChild($root);

try {
    switch ($action) {
        case 'list':
            $stmt = $pdo->query('SELECT id, name, email, phone FROM customers ORDER BY id');
            while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $cust = $xml->createElement('customer');
                foreach ($row as $k => $v) {
                    $cust->appendChild($xml->createElement($k, $v));
                }
                $root->appendChild($cust);
            }
            break;
        case 'get':
            $id = (int)($_GET['id'] ?? 0);
            $stmt = $pdo->prepare('SELECT * FROM customers WHERE id = ?');
            $stmt->execute([$id]);
            if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                $cust = $xml->createElement('customer');
                foreach ($row as $k => $v) $cust->appendChild($xml->createElement($k, $v));
                $root->appendChild($cust);
            } else {
                http_response_code(404);
                $root->setAttribute('error', 'Not found');
            }
            break;
        case 'create':
            $input = file_get_contents('php://input');
            $dom = new DOMDocument();
            $dom->loadXML($input);
            $xpath = new DOMXPath($dom);
            $name  = $xpath->evaluate('string(/customer/name)');
            $email = $xpath->evaluate('string(/customer/email)');
            $phone = $xpath->evaluate('string(/customer/phone)');
            $stmt = $pdo->prepare('INSERT INTO customers (name, email, phone) VALUES (?, ?, ?)');
            $stmt->execute([$name, $email, $phone]);
            $newId = $pdo->lastInsertId();
            $cust = $xml->createElement('customer');
            $cust->appendChild($xml->createElement('id', $newId));
            $cust->appendChild($xml->createElement('name', $name));
            $cust->appendChild($xml->createElement('email', $email));
            $cust->appendChild($xml->createElement('phone', $phone));
            $root->appendChild($cust);
            http_response_code(201);
            break;
        default:
            http_response_code(400);
            $root->setAttribute('error', 'Invalid action');
    }
} catch (Exception $e) {
    http_response_code(500);
    $root->setAttribute('error', $e->getMessage());
}

echo $xml->saveXML();
?>

前端 AJAX 與 XML 處理

<!-- list.html -->
<div id="app">
  <button onclick="loadList()">重新整理</button>
  <table id="grid"><thead><tr><th>ID</th><th>姓名</th><th>Email</th><th>電話</th><th>操作</th></tr></thead><tbody></tbody></table>
  <form id="form" style="display:none; margin-top:1rem;">
    <input type="hidden" name="id">
    <label>姓名: <input name="name" required></label><br>
    <label>Email: <input name="email" type="email" required></label><br>
    <label>電話: <input name="phone"></label><br>
    <button type="submit">儲存</button> <button type="button" onclick="cancelEdit()">取消</button>
  </form>
</div>

<script>
async function loadList() {
    const res = await fetch('api/customers.php?action=list');
    const xml = await res.text();
    const parser = new DOMParser();
    const doc = parser.parseFromString(xml, 'application/xml');
    const tbody = document.querySelector('#grid tbody');
    tbody.innerHTML = '';
    doc.querySelectorAll('customer').forEach(c => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${c.querySelector('id').textContent}</td>
            <td>${c.querySelector('name').textContent}</td>
            <td>${c.querySelector('email').textContent}</td>
            <td>${c.querySelector('phone')?.textContent || ''}</td>
            <td>
                <button onclick="edit(${c.querySelector('id').textContent})">編輯</button>
                <button onclick="del(${c.querySelector('id').textContent})">刪除</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

function edit(id) {
    fetch(`api/customers.php?action=get&id=${id}`)
        .then(r => r.text())
        .then(xml => {
            const doc = new DOMParser().parseFromString(xml, 'application/xml');
            const c = doc.querySelector('customer');
            document.querySelector('[name=id]').value = c.querySelector('id').textContent;
            document.querySelector('[name=name]').value = c.querySelector('name').textContent;
            document.querySelector('[name=email]').value = c.querySelector('email').textContent;
            document.querySelector('[name=phone]').value = c.querySelector('phone')?.textContent || '';
            document.getElementById('form').style.display = 'block';
        });
}

document.getElementById('form').addEventListener('submit', async e => {
    e.preventDefault();
    const fd = new FormData(e.target);
    const xml = `
        <customer>
            <name>${fd.get('name')}</name>
            <email>${fd.get('email')}</email>
            <phone>${fd.get('phone')}</phone>
        </customer>`;
    const url = fd.get('id') ? 'api/customers.php?action=update' : 'api/customers.php?action=create';
    await fetch(url, { method: 'POST', headers: {'Content-Type': 'application/xml'}, body: xml });
    cancelEdit();
    loadList();
});

function cancelEdit() {
    document.getElementById('form').reset();
    document.getElementById('form').style.display = 'none';
}

async function del(id) {
    if (!confirm('確定刪除?')) return;
    await fetch(`api/customers.php?action=delete&id=${id}`, { method: 'POST' });
    loadList();
}

loadList();
</script>

XML 驗證與安全

  • 伺服端使用 DOMDocument::schemaValidate() 驗證輸入 XML 結構。
  • 防止 XXE 攻擊:libxml_disable_entity_loader(true) (PHP 8.0+ 預設關閉)。
  • 輸出前以 htmlspecialchars() 防 XSS,雖本例純 XML 介面較低風險。

現代替代方案

新專案建議改用 JSON + RESTful API 或 GraphQL,開發效率更高、工具鏈更完善。XML 仍適用於需與舊系統整合、需嚴格 Schema 驗證、或涉及文件型資料 (如 Office Open XML) 的場景。

copyright © 萬盛學電腦網 all rights reserved