You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP如何提取XML全部节点键路径 包含嵌套数值索引节点

问题原因

你原有代码的过滤逻辑主动排除了数值类型的键,所以嵌套层级里的数值索引(比如language节点下的序列索引0、1)没有被纳入最终路径输出。

修改后的完整代码

<?php
$array='<?xml version="1.0" encoding="UTF-8"?>
<prestashop xmlns:xlink="http://www.w3.org/1999/xlink">
<country>
    <id>18</id>
    <id_zone xlink:href="https://www.example.com/api/zones/299">299</id_zone>
    <id_currency>0</id_currency>
    <call_prefix>469</call_prefix>
    <iso_code>SE</iso_code>
    <active>1</active>
    <contains_states>0</contains_states>
    <need_identification_number>0</need_identification_number>
    <need_zip_code>1</need_zip_code>
    <zip_code_format>NNN NN</zip_code_format>
    <display_tax_label>1</display_tax_label>
    <name><language id="1" xlink:href="https://www.example.com/api/languages/1">Suède</language><language id="2" xlink:href="https://www.example.com/api/languages/2">Sweden</language></name>
</country>
</prestashop>';
$array1=json_decode(json_encode((array)simplexml_load_string($array,'SimpleXMLElement',LIBXML_NOCDATA)),1);

function getUniqueObjectKeyPaths(array $array, $parentPath = "") {
    $keys = [];
    foreach ($array as $currentKey => $value) {
        // 拼接当前层级的完整路径
        $currentFullPath = $parentPath === "" ? (string)$currentKey : $parentPath . "->" . (string)$currentKey;
        if (!is_array($value)) {
            // 非数组值直接加入路径列表
            $keys[] = $currentFullPath;
        } else {
            // 数组递归获取子路径,合并到结果集
            $nestedKeys = getUniqueObjectKeyPaths($value, $currentFullPath);
            $keys = array_merge($keys, $nestedKeys);
        }
    }
    return $keys;
}
$k=getUniqueObjectKeyPaths($array1);
print_r($k);

输出结果

运行上述代码后会输出包含所有嵌套路径的结果,你需要的country->name->language->0、country->name->language->1会正常展示:

Array
(
    [0] => country->id
    [1] => country->id_zone
    [2] => country->id_currency
    [3] => country->call_prefix
    [4] => country->iso_code
    [5] => country->active
    [6] => country->contains_states
    [7] => country->need_identification_number
    [8] => country->need_zip_code
    [9] => country->zip_code_format
    [10] => country->display_tax_label
    [11] => country->name->language->0
    [12] => country->name->language->1
)

核心修改点

  • 移除了原代码中对键的非数值校验逻辑,数值索引也会被正常保留到路径中
  • 调整了路径拼接逻辑,统一从根节点开始逐层拼接完整路径,避免跨层级拼接逻辑遗漏
  • 所有叶子节点(非数组值)对应的完整路径都会被加入返回结果

内容的提问来源于stack exchange,提问作者Rekha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:06:03