将PHP对象转换为XML的类

时间:2012-02-15 16:10:42

标签: php xml oop

我有以下课程。似乎可以使用具有一个级别的简单对象,但是当对象具有多个级别(多个数组)并且XML全部搞砸时不能正常工作。任何人都可以帮我改进它,这样它可以用于任何物体吗?

class XMLGenerator
{ 
       function __construct($obj,$root, $element, $fullXML = true) {     

          $array = $this->object_2_array($obj);
          $this->output = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
          $this->output .= $this->make($array, $root, $element, $fullXML);

       }

        //convert objects into arrays
        function object_2_array($result){

            $array = array();

            foreach ($result as $key => $value){

                if (is_object($value)){
                    $array[$key]=XMLGenerator::object_2_array($value);
                } elseif (is_array($value)){
                    $array[$key]=XMLGenerator::object_2_array($value);
                } else {
                    $array[$key]=$value;
                }
            }
            return $array;
        }   

       //make XML
       function make($array, $root, $element, $fullXML) {
          if (is_numeric($root)) {
             $xml = "<{$element}>\n";
          } else {
              $xml = "<{$root}>\n";
          }

          foreach ($array as $key => $value) {
             if (is_array($value)) {
                 if ($element == 'options'){  //workaround for orders 3 level problem, need to rethink this - LT
                    $xml .= $this->make($value, $key, $key, $fullXML); 
                 } else {
                    $xml .= $this->make($value, $element, $key, $fullXML);  
                 }              
             } else {

                 //any fields with HTML need wrapping in CDATA
                 if (($key === 'Description')||( $key === 'productDescription' )){
                    $value = '<![CDATA['. $value .']]>';
                 //remove any chars XML doesnt like  
                 } else {
                    $value = htmlentities($value,ENT_QUOTES, 'UTF-8');
                    $value = functions::xml_entities($value);    
                 }
                 //decide on node name

                if (is_numeric($key)) {
                   $xml .= "<{$root}>{$value}</{$root}>\n";
                } else {
                   $xml .= "<{$key}>{$value}</{$key}>\n";
                }           
             }
          }

          if (is_numeric($root)) {
             $xml .= "</{$element}>\n";
          } else {
              $xml .= "</{$root}>\n";
          } 

          return $xml;
       } 


       //save XML to file
       function saveFile($file){
            //create DOM to ensure all XML is valid before writing to file
            $doc = new DOMDocument();
            $doc->loadXML($this->output);

            if ($doc->save("$file")){
                return TRUE;
            } else {
                return FALSE;
            }
       }

}

以下是一个适用于上述类的简单对象。

  

产品对象(       [db_connection:protected] =&gt; 3779074       [prod_id:protected] =&gt; 0       [shopkeeper:protected] =&gt; 0       [fields] =&gt;排列           (

        [productDescription] => Test
        [productName] => Test
        [UPC] => 123
    )
     

以下情况根本无效。

  

订单对象(       [db_connection:protected] =&gt; msSqlConnect对象           (               [con] =&gt;               [dbName] =&gt;           )

[skID:protected] => 89137
[orderID:protected] => 482325
[order] => Array
    (
        [id] => 482325
        [customer] => 491936
        [net] => 1565.98
        [vat] => 274.05
        [billing_address] => Address Object
            (
                [db_connection:protected] => msSqlConnect Object
                    (
                        [con] => 
                        [dbName] => 
                    )

                [custID:protected] => 491936
                [addID:protected] => 156928
                [fields] => Array
                    (
                        [id] => 156928
                        [surname] => test
                        [forename] => test
                        [add1] => 89 testRoad
                        [add2] => 
                        [city] => City
                        [country] => GB
                        [postcode] => POSTCODE
                    )

            )
        [items] => Array
            (
                [0] => Array
                    (
                        [id] => 716549
                        [headerID] => 482325
                        [productID] => 4084620
                        [net] => 22.99
                        [vat] => 4.0233
                        [qty] => 1
                        [options] => Array
                            (
                                [0] => Array
                                    (
                                        [id] => 
                                        [orderDetailsID] => 716549
                                        [optionid] => 763217
                                        [optionCost] => 100
                                        [optionVAT] => 17.5
                                    )

                                [1] => Array
                                    (
                                        [id] => 
                                        [orderDetailsID] => 716549
                                        [optionid] => 763241
                                        [optionCost] => 10
                                        [optionVAT] => 1.75
                                    )

                            )

                    )

                [1] => Array
                    (
                        [id] => 716551
                        [headerID] => 482325
                        [productID] => 3779074
                        [net] => 1400
                        [vat] => 245
                        [qty] => 1
                        [options] => 
                    )
            )
    ) )

非常感谢您的任何帮助。

1 个答案:

答案 0 :(得分:6)

多个级别需要递归处理 - 因为您不知道前面的级别数。在进行递归时,您还需要注意打开哪些XML元素。

您所做的是将PHP对象序列化为XML。你不是第一个需要这个的人,PHP附带了一个符合WDDX规范的XML序列化程序,例如wddx_serialize_value函数:

$object = (object) array('hello' => (object) array('value' => 'world') );

echo wddx_serialize_value($object);

将提供此XML(Demo):

<wddxPacket version='1.0'>
  <header/>
  <data>
    <struct>
      <var name='php_class_name'>
        <string>stdClass</string>
      </var>
      <var name='hello'>
        <struct>
          <var name='php_class_name'>
            <string>stdClass</string>
          </var>
          <var name='value'>
            <string>world</string>
          </var>
        </struct>
      </var>
    </struct>
  </data>
</wddxPacket>

如果需要不同的输出,则需要自己编写序列化。在symfony2(Symfony2 Serializer Component)和Pear(XML_Serializer)中,您可以找到使用XML输出进行序列化的现有PHP代码。