首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 操作 XML 節點屬性完整指南:修改、新增與解析實戰

     編輯:PHP 相關知識

前言

在 PHP 開發中,XML 作為常見的數據交換格式,操作其節點屬性是基礎且重要的技能。本文將通過完整的代碼示例,詳細講解如何使用 PHP 的 DOMDocument 類來修改現有屬性、新增節點屬性,以及解析 XML 文檔結構。

示例 XML 文件結構

首先準備一個典型的配置文件 clientSet.xml 作為操作對象:

<?xml version="1.0" encoding="UTF-8"?>
<clientSet>
  <server url="192.168.0.180" port="1935" />
  <rootPath value="" />
  <homePath value="https://www.example.com" />
  <helpPath value="help.html" />
  <language value="en" />
  <theme value="default" />
  <visibleMarquee value="true" />
  <visibleWhitePaper value="true" />
  <showMemberRoomForGuest value="true" />
  <emotions enabled="true" column="5" autoPlay="false">
    <item name="Birthday" src="cartoon/movie/birthday.swf" thumb="cartoon/preview/birthday-small.swf" duration="15"/>
    <item name="Boom" src="cartoon/movie/boom.swf" thumb="cartoon/preview/boom-small.swf" duration="6"/>
    <item name="Bubble" src="cartoon/movie/bubble.swf" thumb="cartoon/preview/bubble-small.swf" duration="7.5"/>
    <item name="Cry" src="cartoon/movie/cry.swf" thumb="cartoon/preview/cry-small.swf" duration="5.4"/>
    <item name="Doggie" src="cartoon/movie/doggie.swf" thumb="cartoon/preview/doggie-small.swf" duration="13"/>
    <item name="Greeting" src="cartoon/movie/greeting.swf" thumb="cartoon/preview/greeting-small.swf" duration="7.4"/>
    <item name="Football" src="cartoon/movie/football.swf" thumb="cartoon/preview/football-small.swf" duration="2.2"/>
  </emotions>
</clientSet>

核心操作代碼解析

1. 修改現有節點屬性

以下代碼演示如何定位 <emotions> 節點下的 <item> 子節點,並將 name="Birthday" 修改為 name="nBirthday":

<?php
$dom = new DOMDocument('1.0');
$dom->load('clientSet.xml');

// 獲取 emotions 節點
$emotions = $dom->getElementsByTagName('emotions')->item(0);

// 獲取所有 item 子節點
$items = $emotions->getElementsByTagName('item');

// 遍歷查找目標節點
foreach ($items as $item) {
    foreach ($item->attributes as $attr) {
        if ($attr->nodeValue === 'Birthday') {
            // 修改屬性值
            $item->setAttribute('name', 'nBirthday');
            break;
        }
    }
}

$dom->save('clientSet.xml');
?>

2. 新增節點及屬性

向 <emotions> 節點追加一個新的 <item> 節點:

<?php
$dom = new DOMDocument('1.0');
$dom->load('clientSet.xml');

$emotions = $dom->getElementsByTagName('emotions')->item(0);

// 創建新節點
$newItem = $dom->createElement('item');
$newItem->setAttribute('name', 'NewYear');
$newItem->setAttribute('src', 'cartoon/movie/newyear.swf');
$newItem->setAttribute('thumb', 'cartoon/preview/newyear-small.swf');
$newItem->setAttribute('duration', '10');

// 追加到父節點
$emotions->appendChild($newItem);

$dom->save('clientSet.xml');
?>

3. 解析 XML 並讀取所有屬性

通用的 XML 解析模板,適用於任意結構:

<?php
$dom = new DOMDocument('1.0');
$dom->load('data.xml');

$root = $dom->getElementsByTagName('videos')->item(0);
$videos = $root->getElementsByTagName('video');

// 讀取並輸出所有屬性
foreach ($videos as $video) {
    foreach ($video->attributes as $attr) {
        echo $attr->nodeName . ': ' . $attr->nodeValue . '<br/>';
    }
    echo '<hr/>';
}

// 新增一條記錄
$newVideo = $dom->createElement('video');
$newVideo->setAttribute('title', 'PHP教程');
$newVideo->setAttribute('src', 'video/php_tutorial.mp4');
$newVideo->setAttribute('img', 'thumb/php.jpg');
$root->appendChild($newVideo);

$dom->save('data.xml');
?>

4. 條件修改:根據屬性值更新節點

針對特定條件(如 img="1")進行批量修改:

<?php
$doc = new DOMDocument();
$doc->load('data.xml');

$root = $doc->getElementsByTagName('videos')->item(0);
$videos = $root->getElementsByTagName('video');

foreach ($videos as $video) {
    foreach ($video->attributes as $attr) {
        // 找到 img 屬性且值為 "1" 的節點
        if ($attr->nodeName === 'img' && $attr->nodeValue === '1') {
            $video->setAttribute('img', 'image');
            $doc->save('data.xml');
            break; // 找到即退出內層循環
        }
    }
}
?>

關鍵技術點總結

  • DOMDocument:PHP 內置的 XML/HTML 解析器,支援 XPath、命名空間等高級功能
  • getElementsByTagName():按標籤名獲取節點列表,返回 DOMNodeList 對象
  • attributes 屬性:節點的屬性集合,可遍歷訪問每個屬性的 nodeName 和 nodeValue
  • setAttribute():修改或新增屬性,若屬性不存在則自動創建
  • createElement() + appendChild():創建新節點並掛載到 DOM 樹中
  • save():將修改後的 DOM 寫回文件,完成持久化

最佳實踐建議

  1. 操作前先備份原始 XML 文件
  2. 大型 XML 文件建議使用 XMLReader(流式解析)避免記憶體溢出
  3. 修改屬性前務必判斷節點是否存在,避免報錯
  4. 涉及用戶輸入的屬性值需經過轉義,防止 XML 注入

掌握這些核心 API,即可輕鬆應對 PHP 中的 XML 節點屬性增刪改查需求。實際項目中可根據 XML 複雜度選擇 DOM 或 SimpleXML、XMLReader 等不同解析器。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved