Convert XML to Object function สำหรับแปลง XML เป็น Object

PHP Result Center PHP Result Center เป็นหมวด ที่ไว้รวบรวม โปรแกรม Code php Javascript CSS CMS

Moderator: mindphp, ผู้ดูแลกระดาน

ภาพประจำตัวสมาชิก
mindphp
ผู้ดูแลระบบ MindPHP
ผู้ดูแลระบบ MindPHP
โพสต์: 41384
ลงทะเบียนเมื่อ: 22/09/2008 6:18 pm
ติดต่อ:

Convert XML to Object function สำหรับแปลง XML เป็น Object

โพสต์ที่ยังไม่ได้อ่าน โดย mindphp »

Convert XML to Object function สำหรับแปลง XML เป็น Object

โค้ด: เลือกทั้งหมด

<?php

function parseXMLtoObject($xml) {
   $obj = new stdClass();
   
   $xml = explode("\n",$xml);
   
   $main_n = '';
   
   foreach ($xml as $x) {
      $first_n = false;
      $close_n = false;
      if ($x != '') {
         $start_val = (strpos($x,">")+1);
         $end_val = strrpos($x,"<") - $start_val;
         $start_n = (strpos($x,"<")+1);
         $end_n = strpos($x,">") - $start_n;
         $n = strtolower(substr($x,$start_n,$end_n));
         if (substr_count($x,"<") == 1) {
            if (!empty($main_n) && !stristr($n,"/")) {
               $submain_n = $n;
               $first_n = true;
            } else {
               $main_n = $n;
               $submain_n = '';
               $first_n = true;
            }
         }
         if (!empty($submain_n) && stristr($submain_n,"/")) {
            $submain_n = '';
            $first_n = false;
            $close_n = true;
         }
         if (!empty($main_n) && stristr($main_n,"/")) {
            $main_n = '';
            $submain_n = '';
            $first_n = false;
            $close_n = true;
         }
         $value = substr($x,$start_val,$end_val);
         if (!$close_n) {
            if (empty($main_n)) {
               $obj->$n = $value;
            } else {
               if ($first_n) {
                  if (empty($submain_n)) {
                     $obj->$main_n = new stdClass();
                  } else {
                     $obj->$main_n->$submain_n = new stdClass();
                  }
               } else {
                  if (!empty($value)) {
                     if (empty($submain_n)) {
                        $obj->$main_n->$n = $value;
                     } else {
                        $obj->$main_n->$submain_n->$n = $value;
                     }
                  }
               }
            }
         }
      }
   }
   
   return $obj;
}

?>
ลองดูนะครับ เผื่อมีประโยชน์ ใครมีอะไร ดีๆก็เอามาแนะำนำกันบ้างนะครับ
ติดตาม VDO: http://www.youtube.com/c/MindphpVideoman
ติดตาม FB: https://www.facebook.com/pages/MindphpC ... 9517401606
หมวดแชร์ความรู้: https://www.mindphp.com/forums/viewforum.php?f=29
รับอบรม และพัฒนาระบบ: https://www.mindphp.com/forums/viewtopic.php?f=6&t=2042
  • Similar Topics
    ตอบกลับ
    แสดง
    โพสต์ล่าสุด

ผู้ใช้งานขณะนี้

สมาชิกกำลังดูบอร์ดนี้: ไม่มีสมาชิกใหม่ และบุคลทั่วไป 72