Răsfoiți Sursa

添加json转xml

visuddhinanda 2 ani în urmă
părinte
comite
dad029a79f
2 a modificat fișierele cu 77 adăugiri și 0 ștergeri
  1. 50 0
      app/Console/Commands/TestJsonToXml.php
  2. 27 0
      app/Tools/Tools.php

+ 50 - 0
app/Console/Commands/TestJsonToXml.php

@@ -0,0 +1,50 @@
+<?php
+
+namespace App\Console\Commands;
+
+use Illuminate\Console\Command;
+use App\Tools\Tools;
+
+class TestJsonToXml extends Command
+{
+    /**
+     * The name and signature of the console command.
+     *
+     * @var string
+     */
+    protected $signature = 'test:json.to.xml';
+
+    /**
+     * The console command description.
+     *
+     * @var string
+     */
+    protected $description = 'Command description';
+
+    /**
+     * Create a new command instance.
+     *
+     * @return void
+     */
+    public function __construct()
+    {
+        parent::__construct();
+    }
+
+    /**
+     * Execute the console command.
+     *
+     * @return int
+     */
+    public function handle()
+    {
+        $array = [
+            'pali'=>['status'=>'7','value'=>'bārāṇasiyaṃ'],
+            'real'=>['status'=>'7','value'=>'bārāṇasiyaṃ'],
+            'id'=>'p171-2475-10'
+        ];
+        $xml = Tools::JsonToXml($array);
+        $this->info($xml);
+        return 0;
+    }
+}

+ 27 - 0
app/Tools/Tools.php

@@ -9,4 +9,31 @@ class Tools{
                             ["a","i","u","n","n","t","d","n","l","m"], $strIn);
             return ($out);
         }
+    public static function JsonToXml($inArray){
+        $xmlObj = simplexml_load_string("<word></word>");
+        function convert($array,$xml){
+            foreach ($array as $key => $line) {
+                # code...
+                if(!is_array($line)){
+                    $data = $xml->addChild($key,$line);
+                }else{
+                    if(isset($line['value'])){
+                        $value = $line['value'];
+                        unset($line['value']);
+                    }else{
+                        $value = "";
+                    }
+                    $obj = $xml->addChild($key,$value);
+                    if(isset($line['status'])){
+                        $obj->addAttribute('status',$line['status']);
+                        unset($line['status']);
+                    }
+                    convert($line,$obj);
+                }
+            }
+            return $xml;
+        }
+        $xmlDoc = convert($inArray,$xmlObj);
+        return $xmlDoc->asXml();
+    }
 }