简体   繁体   English

使用 php 将递归 xml 转换为 Json

[英]Transform recursive xml into Json with php

I'm trying to transform XML into Json via PHP and I don't know how to serialize objects.我正在尝试通过 PHP 将 XML 转换为 Json ,但我不知道如何序列化对象。 Basically, I have in input an XML file (file.xml) with a recursive structure and I would like to transpose it into Json (out.json).基本上,我输入了一个具有递归结构的 XML 文件(file.xml),我想将其转换为 Json(out.json)。

xml file sample: xml 文件示例:

<Transfer>
 <Name>Transfer</Name>
 <Title>Transfer + Date</Title>
 <Level1>
   <Name>Item 1</Name>
   <Title>Title 1</Title>
   <className>middle-level</className>
   <Level2>
      <Name>Item 1.1</Name>
      <Title>Title 1.1</Title>
      <className>product-dept</className>
   </Level2>
   <Level2>
      <Name>Item 1.2</Name>
      <Title>Title 1.2</Title>
      <className>product-dept</className>
      <Level3>
          <Name>Item 1.2.1</Name>       
          <Title>Title 1.2.1</Title>            
          <className>pipeline1</className>        
      </Level3>        
      <Level3>            
          <Name>Item 1.2.2</Name>            
          <Title>Title 1.2.2</Title>            
          <className>pipeline1</className>        
      </Level3>
    </Level2>  
  </Level1>  
  <Level1>    
    <Name>Item 2</Name>    
    <Title>Title 2</Title>    
    <className>middle-level</className>  
  </Level1>
</Transfer>

Json output desired: Json output 需要:

{
    'name': 'Transfer',
    'title': 'transfer Date',
    'children': [
      { 'name': 'Item 1', 'title': 'Title 1', 'className': 'middle-level',
        'children': [
          { 'name': 'Item 1.1', 'title': 'Title 1.1', 'className': 'product-dept' },
          { 'name': 'Item 1.2', 'title': 'Title 1.2', 'className': 'product-dept',
            'children': [
              { 'name': 'Item 1.2.1', 'title': 'Title 1.2.1', 'className': 'pipeline1' },
              { 'name': 'Item 1.2.2', 'title': 'Title 1.2.2', 'className': 'pipeline1' },
            ]
          }
        ]
      },
      { 'name': 'Item 2', 'title': 'Title 2', 'className': 'middle-level'}
    ]
  }

All this with php code:所有这些都使用 php 代码:

$xml = simplexml_load_file("file.xml");
$result = [];

foreach ($xml->Level1 as $value) 
{
    
    $child = [];
    $child['Name'] = (string)$value->Name;
    $child['Title'] = (string)$value->Title;
    $child['className'] = (string)$value->className;


    foreach ($xml->Level2 as $level2)
    {
        $child = [];
        $child['Level2'] = (string)$value->Level2->Name;
    }

    $result[] = $child;
    
}

$json_string = json_encode($result);
print_r($json_string);

Currently, I'm just transforming a part of the graph but I don't understand how to do more.目前,我只是在转换图表的一部分,但我不明白如何做更多。 I think that what I want to do is not too complex but I am blocked.我认为我想做的事情并不太复杂,但我被阻止了。

Thanks for the help.谢谢您的帮助。

When working with a structure of unkown depth, the stack is usually your best friend:当使用未知深度的结构时,堆栈通常是你最好的朋友:

function xmlToJson($node, $level = 1)
{
    $children = [];
    if (isset($node->${'Level' . $level})) {
        foreach ($node->${'Level' . $level} as $value) {
            $children[] = [
                'name' => (string)$value->Name,
                'title' => (string)$value->Title,
                'className' => (string)$value->className,
                'children' => xmlToJson($value, $level + 1),
            ];
        }
    }

    return $children;
}

This code will start at level one and fetch all the names, titles and classNames.此代码将从第一级开始并获取所有名称、标题和类名。 Then it calls itself, creating a recursive function .然后它调用自己,创建一个递归 function Because of this, you need to make sure that level exists, hence the if (isset(...)) before actually accessing the level.因此,您需要确保该级别存在,因此在实际访问该级别之前需要if (isset(...))

The function will terminate if it stops calling itself, which is when there are no more levels to descent down to.如果 function 停止调用自己,即没有更多级别可以下降到时,它将终止。

Try this尝试这个

    $xml = simplexml_load_string($xml);
    $result = [];
    $result['name'] = (string)$xml->Name;
    $result['title'] = (string)$xml->Title;

    foreach ($xml->Level1 as $value)
    {

        $child = [];
        $item = [];
        $item['name'] = (string)$value->Name;
        $item['title'] = (string)$value->Title;
        $item['className'] = (string)$value->className;

        foreach ($value->Level2 as $level2)
        {
            $child2 = [];
            foreach ($level2->Level3 as $level3) {
                $child2[] = array(
                    'name' => (string)$level3->Name,
                    'title' => (string)$level3->Title,
                    'className' => (string)$level3->className,
                );
            }
            $child[] = array(
                'name' => (string)$level2->Name,
                'title' => (string)$level2->Title,
                'className' => (string)$level2->className,
                'children' => $child2,
            );
        }

        $item['children'] = $child;
        $result['children'][] = $item;
    }
    $json_string = json_encode($result);
    print_r($json_string);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM