Pandemum
Pandemum

Reputation: 53

Object to XML changing the names of the nodes

I have the object in php like this:

object(stdClass)[16]
  public 'L1' => 
    object(stdClass)[17]
      public 'int' => 
        array (size=2)
          0 => int 1
          1 => int 2
  public 'L2' => string '52' (length=2)
  public 'R' => string '2' (length=1)

Which i can convert to XML and i get:

<data>
 <L1>
   <int>
     <node>1</node>
     <node>2</node>
   </int>
 </L1>
 <L2>52</L2>
 <R>2</R>
</data>

The problem is that i want to get rid of the names of the nodes and the node . In the final i want my XML to look like this:

<data>
 <param1>1</param1>
 <param2>2</param2>
 <param3>52</param3>
 <param4>2</param4>
</data>

Can anyone suggest the way i can do it ?

Thank you in advance.

Here is the class for creating the XML:

<?php

class XMLSerializer {

    // functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/

    public static function generateValidXmlFromObj(stdClass $obj, $node_block='data', $node_name='node') {
        $arr = get_object_vars($obj);
        return self::generateValidXmlFromArray($arr, $node_block, $node_name);
    }

    public static function generateValidXmlFromArray($array, $node_block='data', $node_name='node') {
        $xml = '<?xml version="1.0" encoding="UTF-8" ?>';

        $xml .= '<' . $node_block . '>';
        $xml .= self::generateXmlFromArray($array, $node_name);
        $xml .= '</' . $node_block . '>';

        return $xml;
    }

    private static function generateXmlFromArray($array, $node_name) {
        $xml = '';

        if (is_array($array) || is_object($array)) {
            foreach ($array as $key=>$value) {
                if (is_numeric($key)) {
                    $key = $node_name;
                }

                $xml .= '<' . $key . '>' . self::generateXmlFromArray($value, $node_name) . '</' . $key . '>';
            }
        } else {
            $xml = htmlspecialchars($array, ENT_QUOTES);
        }

        return $xml;
    }

}

And the code:

header ("Content-Type:text/xml");

include 'tamo.wss.php';
include 'xml_class.php';

$user = $_GET['id'];

$client = new SoapClient("Wsdl_Service", $options);

$client->__setSoapHeaders(Array(new WsseAuthHeader("login", "password")));

$param['ns1:l0'] = $user;
$encodded = new SoapVar($param, SOAP_ENC_OBJECT);

$result = $client->GetAttributes($encodded);

$xml = XMLSerializer::generateValidXmlFromObj($result->GetAttributesResult->Result->SingleAttribute);

echo $xml;

Upvotes: 1

Views: 147

Answers (1)

silkfire
silkfire

Reputation: 25945

If I've understood your problem correctly, you can solve it this way.

$index = 1;

$xml = '<data>';

foreach(get_object_vars($result->GetAttributesResult->Result->SingleAttribute) as $value) {
   $xml .= '<param' . $index . '>' . $value . '</param' . $index++ . '>';
}

$xml .= '</data>';

Upvotes: 1

Related Questions