我正在编写一个 php 应用程序来操作 XML 文件。我尝试了 Perl XML 序列化器/反序列化器来转换 XML->php obj->json 进行操作然后将 json 转换回 xml 以打印出来。
这是原始 XML 的示例
<module name="AssignId" active="true" description="user description">
<dict name="params">
<entry key="Adds">
...
</entry>
</dict>
</module>
转换为 JSON 如下所示:
{"name":"AssignId","active":"true","description":"add draggable class to figure","dict":{"name":"params","entry":[{"key":"Adds" ...
}}
最终结果 XML 如下所示:
<name>AssignId</name>
<active>true</active>
<description>add draggable class to figure</description>
<dict>
<name>params</name>
<entry>
<XML_Serializer_Tag>
<key>Adds</key>
...
</XML_Serializer_Tag>
</entry>
</dict>
</name>
这是我的 2 节课
class JSON_toXML {
var $jsonObj,
$phpObj,
$serializer;
public function __construct($options, $file_path) {
$this->serializer = new XML_Serializer($options);
$serializedDoc = $this->serializer->serialize(json_decode($file_path));
if ($serializedDoc === true) {
$this->jsonObj = $this->serializer->getSerializedData();
} else {
$this->jsonObj = NULL;
}
}
public function print_obj() {
echo "<pre>";
echo($this->jsonObj);
echo "</pre>";
}
}
class XML_toJSON {
var $phpObj,
$jsonObj,
$unserializer;
public function __construct($options, $file_path) {
$this->unserializer = &new XML_Unserializer($options);
$unserializedDoc = $this->unserializer->unserialize($file_path, true);
$this->phpObj = $this->unserializer->getUnserializedData();
$this->jsonObj = json_encode($this->phpObj);
}
public function print_phpObj() {
echo "<pre>";
print_r($this->phpObj);
echo "</pre>";
}
public function get_phpObj() {
return $this->phpObj;
}
public function print_jsonObj() {
echo $this->jsonObj;
}
public function get_jsonObj() {
return $this->jsonObj;
}
}
我想知道如何保持最终结果 XML 与原始格式相同?也许有更好的方法来做到这一点?谢谢!!!