What is the best way to take a given PHP object and serialize it as XML? I am looking at simple_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around.
相关问题
- Views base64 encoded blob in HTML with PHP
- Laravel Option Select - Default Issue
- Illegal to have multiple roots (start tag in epilo
- PHP Recursively File Folder Scan Sorted by Modific
- Can php detect if javascript is on or not?
take a look at PEAR's XML_Serializer package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.
Should do the trick
While I agree with @philfreo and his reasoning that you shouldn't be dependant on PEAR, his solution is still not quite there. There are potential issues when the key could be a string that contains any of the following characters:
Any of these will throw off the format, as XML uses these characters in its grammar. So, without further ado, here is a simple solution to that very possible occurrence:
Here is a sample usage:
Notice that the key names are stored in the varname attribute (html encoded), and even the type is stored, so symmetric de-serialization is possible. There is only one issue with this: it will not serialize classes, only the instantiated object, which will not include the class methods. This is only functional for passing "data" back and forth.
I hope this helps someone, even though this was answered long ago.
take a look at my version
not quite an answer to the original question, but the way i solved my problem with this was by declaring my object as:
as opposed to:
before i started adding any values!
Use a dom function to do it: http://www.php.net/manual/en/function.dom-import-simplexml.php
Import the SimpleXML object and then save. The above link contains an example. :)
In a nutshell:
Use recursive method, like this:
Here the complete example: http://www.tyrodeveloper.com/2018/09/convertir-clase-en-xml-con-php.html