2016-10-07 2 views
0

Мне нужно преобразовать данные JSON в формат HTML. У меня проблемы с добавлением дочерних элементов в правильном порядке. Все элементы добавляются последовательно, но порядок должен быть таким же, как в структуре JSON. Как я могу добавить в правильном порядке?PHP JSON данные для преобразования HTML

Пример JSON:

{ 
    "tag": "html", 
    "children": [ 
     { 
      "tag": "body", 
      "children": [ 
       { 
        "tag": "form", 
        "class": "form-horizontal", 
        "children": [ 
         { 
          "tag": "fieldset", 
          "children": [ 
           { 
            "tag": "legend", 
            "html": "Form Name" 
           }, 
           { 
            "tag": "div", 
            "class": "control-group", 
            "children": [ 
             { 
              "tag": "label", 
              "class": "control-label", 
              "for": "textinput-0", 
              "html": "Text Input" 
             }, 
             { 
              "tag": "div", 
              "class": "controls", 
              "children": [ 
               { 
                "tag": "input", 
                "id": "textinput-0", 
                "name": "textinput-0", 
                "type": "text", 
                "placeholder": "placeholder", 
                "class": "input-xlarge" 
               }, 
               { 
                "tag": "p", 
                "class": "help-block", 
                "html": "help" 
               } 
              ] 
             } 
            ] 
           }, 
           { 
            "tag": "div", 
            "class": "control-group", 
            "children": [ 
             { 
              "tag": "label", 
              "class": "control-label", 
              "for": "singlebutton-0", 
              "html": "Single Button" 
             }, 
             { 
              "tag": "div", 
              "class": "controls", 
              "children": [ 
               { 
                "tag": "button", 
                "id": "singlebutton-0", 
                "name": "singlebutton-0", 
                "class": "btn btn-primary", 
                "html": "Button" 
               } 
              ] 
             } 
            ] 
           } 
          ] 
         } 
        ] 
       } 
      ] 
     } 
    ] 
} 

То, что я получил до сих пор:

<html><body> 
<form class="form-horizontal"> 
<fieldset> 
<legend>Form Name 
<div class="control-group"> 
    <label class="control-label" for="textinput-0">Text Input 
    <div class="controls"> 
    <input id="textinput-0" name="textinput-0" type="text" placeholder="placeholder" class="input-xlarge"> 
    </div> 
    </label> 
</div> 
</legend> 
</fieldset> 
</form> 
</body></html> 

Правильный вывод должен быть:

<html><body> 
<form class="form-horizontal" > 
<fieldset> 
<legend>Form Name</legend> 
<div class="control-group"> 
    <label class="control-label" for="textinput-0">Text Input</label> 
    <div class="controls"> 
    <input id="textinput-0" name="textinput-0" type="text" placeholder="placeholder" class="input-xlarge"> 
    <p class="help-block">help</p> 
    </div> 
</div> 
<div class="control-group"> 
    <label class="control-label" for="singlebutton-0">Single Button</label> 
    <div class="controls"> 
    <button id="singlebutton-0" name="singlebutton-0" class="btn btn-primary">Button</button> 
    </div> 
</div> 
</fieldset> 
</form> 
</body></html> 

Мой PHP код:

$dom = new DOMDocument; 
$rootelem = $dom; 

$obj = json_decode($json_content, true); 
parse_to_html($obj); 

function parse_to_html($arr) { 
    global $dom; 
    global $rootelem; 

    foreach ($arr as $key => $val) { 
     if (is_array($val)) { 
      parse_to_html($val); 
     } else { 
      if ($key == "tag") { 
       $rootelem = $rootelem->appendChild($dom->createElement($val)); 
      } else if ($key == "html") { 
       $rootelem->textContent = $val; 
      } else { //attribute 
       $domAttribute = $dom->createAttribute($key); 
       $domAttribute->value = $val; 
       $rootelem->appendChild($domAttribute); 
      } 
     } 
    } 
} 

$dom->formatOutput = true; 
print $dom->saveHTML(); 
+1

Люди, которые попытаются помочь вам, заслуживают минимального рассмотрения. Можете ли вы правильно отформатировать раздел «Что я получил до сих пор»? Он не читается только в двух строках. –

+0

@ AlFoиceѫ конечно, сделано. –

+0

В том же формате, что и предполагаемый результат, также помогает. Теперь это сделано – wasthishelpful

ответ

0

Вот мое собственное решение. Я добавил параметр $level, который содержит уровень элемента в массиве. Поэтому я могу добавить к соответствующему элементу. Также глобальный массив $nod, который ссылается на созданные узлы.

function parse_to_html($arr, $level = 1) { 
    global $dom; 
    global $nod; 

    foreach ($arr as $key => $val) { 
     if (is_array($val)) { 
      parse_to_html($val, $level + 1); 
     } else { 
      if ($key == "tag") { 
       $nod[$level] = $dom->createElement($val); 
       $nod[$level-2]->appendChild($nod[$level]); 
      } else if ($key == "html") { 
       $nod[$level]->nodeValue = $val; 
      } else { //attribute 
       $domAttribute = $dom->createAttribute($key); 
       $domAttribute->value = $val; 
       $nod[$level]->appendChild($domAttribute); 
      } 

     } 
    } 
}