我在php中有这样的对象:
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)
我可以将其转换为XML并获得:
<data>
<L1>
<int>
<node>1</node>
<node>2</node>
</int>
</L1>
<L2>52</L2>
<R>2</R>
</data>
问题是我想摆脱节点和节点的名称。在最后,我希望我的XML看起来像这样:
<data>
<param1>1</param1>
<param2>2</param2>
<param3>52</param3>
<param4>2</param4>
</data>
有人能建议我这样做吗?
提前谢谢。
以下是创建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;
}
}
代码:
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;
答案 0 :(得分:1)
如果我已正确理解您的问题,您可以通过这种方式解决问题。
$index = 1;
$xml = '<data>';
foreach(get_object_vars($result->GetAttributesResult->Result->SingleAttribute) as $value) {
$xml .= '<param' . $index . '>' . $value . '</param' . $index++ . '>';
}
$xml .= '</data>';