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

PHP如何实现XML转格式化JSON,达到在线转换器的同等效果

XML转指定格式JSON的PHP实现方案

需要将指定XML数据转换为符合要求的格式化JSON后输出到API,原有转换代码效果不符合预期,以下是完整的调整方案。

原始XML结构

<?xml version="1.0" encoding="utf-8"?>
<CatapultVariableSet>
  <Variable
    Name="Email"
    Comment=""
    EvaluatedDefinition="info@yourcompany.com">info@yourcompany.com</Variable>
  <Variable
    Name="StreetAddress"
    Comment=""
    EvaluatedDefinition="1234 Lorem Ipsum Ave.">1234 Lorem Ipsum Ave.</Variable>
  <Variable
    Name="MiR_250"
    Comment=""
    EvaluatedDefinition="MiR250">MiR250</Variable>
</CatapultVariableSet>

期望输出的JSON格式

[
   {
      "Name": "Email",
      "Comment": "",
      "EvaluatedDefinition": "info@yourcompany.com",
      "#text": "info@yourcompany.com"
   },
   {
      "Name": "StreetAddress",
      "Comment": "",
      "EvaluatedDefinition": "1234 Lorem Ipsum Ave.",
      "#text": "1234 Lorem Ipsum Ave."
   },
   {
      "Name": "MiR_250",
      "Comment": "",
      "EvaluatedDefinition": "MiR250",
      "#text": "MiR250"
   }
]

原有问题代码

function my_awesome_func() {
    $myfile = fopen("fildestination", "r") or die("Unable to open file!");
    $output = fread($myfile,filesize("fildestination"));
    fclose($myfile);
    
    $json = json_encode($output);
    $jsondecoded = json_decode($json, TRUE);
    $simplexml = simplexml_load_string($jsondecoded);
    $vars = $simplexml[0]->Variable;
    $simpledecode = json_encode($simplexml, JSON_PRETTY_PRINT);
   
    foreach($vars as $v){
        $array = array(
            "v_name" => $v["Name"][0],
            "v_value" => $v["EvaluatedDefinition"][0]
        );
        $encodej = json_encode($array, JSON_PRETTY_PRINT);
        echo $encodej;

    }
}

修正后可实现目标效果的代码

function my_awesome_func() {
    // 读取XML文件内容
    $xmlContent = file_get_contents("fildestination") or die("Unable to open file!");
    $simplexml = simplexml_load_string($xmlContent);
    
    // 初始化结果数组
    $result = [];
    
    // 遍历所有Variable节点
    foreach ($simplexml->Variable as $variable) {
        // 转换节点属性为数组
        $item = (array)$variable->attributes();
        $item = $item['@attributes'];
        // 追加节点文本内容为#text字段
        $item['#text'] = (string)$variable;
        // 加入结果数组
        $result[] = $item;
    }
    
    // 输出格式化JSON
    echo json_encode($result, JSON_PRETTY_PRINT);
}

核心调整说明

  • 移除了XML读取后多余的JSON编解码步骤,直接加载XML内容提升效率
  • 统一收集所有变量节点信息到单个数组,避免分开输出多个独立JSON对象
  • 完整保留所有属性字段,追加#text字段存储节点文本内容,和预期格式完全对齐

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 02:57:03