蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行 PHP 8.4 DOMDocument 树层级、load/saveXML 与空白文本节点过滤实测

PHPWindows x64、PHP 8.4 本地 CLI 环境。explore-xml-dom.php
explore-xml-dom.php143 行
<?php
declare(strict_types=1);

$cases = [];

function add_case(array &$cases, string $name, mixed $expected, mixed $actual): void {
    $cases[] = [
        'name' => $name,
        'passed' => ($actual === $expected),
        'expected' => $expected,
        'actual' => $actual,
    ];
}

// Case 1: Tree levels for <from>Jani</from>
$fragDoc = new DOMDocument();
$fragDoc->loadXML("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n<from>Jani</from>");
$root = $fragDoc->documentElement;
$textNode = $root->firstChild;

add_case(
    $cases,
    'dom_tree_levels_from_fragment',
    [
        'level1_node_name' => '#document',
        'level1_node_type' => XML_DOCUMENT_NODE,
        'level2_root_name' => 'from',
        'level3_text_name' => '#text',
        'level3_text_value' => 'Jani',
    ],
    [
        'level1_node_name' => $fragDoc->nodeName,
        'level1_node_type' => $fragDoc->nodeType,
        'level2_root_name' => $root->nodeName,
        'level3_text_name' => $textNode->nodeName,
        'level3_text_value' => $textNode->nodeValue,
    ]
);

// Write note.xml to a temp file and clean up in finally
$noteXml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
    . "<note>\n"
    . "<to>Tove</to>\n"
    . "<from>Jani</from>\n"
    . "<heading>Reminder</heading>\n"
    . "<body>Don't forget me this weekend!</body>\n"
    . "</note>\n";

$tmpFile = tempnam(sys_get_temp_dir(), 'dom_note_');
if ($tmpFile === false) {
    throw new RuntimeException('Failed to create temp file');
}

try {
    file_put_contents($tmpFile, $noteXml);

    // Case 2: load() and saveXML()
    $doc = new DOMDocument();
    $doc->load($tmpFile);
    $saved = $doc->saveXML();
    $joinedText = preg_replace('/\r?\n/', '', $doc->documentElement->textContent);

    add_case(
        $cases,
        'dom_load_file_and_savexml',
        [
            'has_xml_decl' => true,
            'has_body_tag' => true,
            'concat_text' => "ToveJaniReminderDon't forget me this weekend!",
        ],
        [
            'has_xml_decl' => str_starts_with($saved, '<?xml version="1.0" encoding="ISO-8859-1"?>'),
            'has_body_tag' => str_contains($saved, "<body>Don't forget me this weekend!</body>"),
            'concat_text' => $joinedText,
        ]
    );

    // Case 3: Traversing childNodes exposes whitespace #text nodes between elements
    $rawNodes = [];
    foreach ($doc->documentElement->childNodes as $item) {
        $rawNodes[] = $item->nodeName . '=' . trim($item->nodeValue);
    }
    add_case(
        $cases,
        'dom_traverse_childnodes_whitespace',
        [
            'total_child_nodes' => 9,
            'text_node_count' => 5,
            'nodes' => [
                '#text=',
                'to=Tove',
                '#text=',
                'from=Jani',
                '#text=',
                'heading=Reminder',
                '#text=',
                "body=Don't forget me this weekend!",
                '#text=',
            ],
        ],
        [
            'total_child_nodes' => count($rawNodes),
            'text_node_count' => count(array_filter($rawNodes, static fn(string $s): bool => str_starts_with($s, '#text='))),
            'nodes' => $rawNodes,
        ]
    );

    // Case 4: Filtering XML_ELEMENT_NODE vs preserveWhiteSpace = false
    $elementsOnly = [];
    foreach ($doc->documentElement->childNodes as $item) {
        if ($item->nodeType === XML_ELEMENT_NODE) {
            $elementsOnly[$item->nodeName] = $item->nodeValue;
        }
    }

    $compactDoc = new DOMDocument();
    $compactDoc->preserveWhiteSpace = false;
    $compactDoc->load($tmpFile);
    add_case(
        $cases,
        'dom_filter_element_nodes_only',
        [
            'elements' => [
                'to' => 'Tove',
                'from' => 'Jani',
                'heading' => 'Reminder',
                'body' => "Don't forget me this weekend!",
            ],
            'compact_child_count' => 4,
        ],
        [
            'elements' => $elementsOnly,
            'compact_child_count' => $compactDoc->documentElement->childNodes->length,
        ]
    );
} finally {
    if (is_file($tmpFile)) {
        unlink($tmpFile);
    }
}

echo json_encode(['version' => PHP_VERSION, 'cases' => $cases], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . "\n";
本例需在 Windows x64、PHP 8.4 本地 CLI 环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、PHP 8.4 本地 CLI 环境。

入口文件:projects/php-xml-dom-lab/explore-xml-dom.php

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-xml-dom.php,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、PHP 8.4 本地 CLI 环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:PHP

课程关联工程包(登记关联95章) · 含当前章节或实例 · mbskycom202612a1232.zip

下载课程关联工程包:PHP

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1315.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习