PHP XML 性能和序列化()
我有一个 XML 文件,其中包含一些对象的结构。对象是这样的:
class Object:
{
private $name;
private $info;
private $$items;
}
其中$items是对象数组,所以是递归的。 截至目前,当我必须列出项目时,我使用 simplexml 在元素内进行迭代并显示它们。 我的问题是:
1)如果我解析 XML 并将数据转换为对象而不是使用纯 XML,是否会影响页面的整体性能?考虑到用户加载的每个页面都必须加载项目,它会减慢太多吗?
2)像我定义的那样序列化()递归对象是个好主意吗?
I have an XML file which contains the structure of some objects. The object is like this:
class Object:
{
private $name;
private $info;
private $items;
}
Where $items is an array of objects, so it is recursive.
As of now, when I have to list the items I use simplexml to iterate within the elements and show them.
My questions are:
1) If I parse the XML and convert the data into the object instead of working with pure XML, would it affect the overall performance of the pages all that much? Will it slow down too much considering that every page the user loads he will have to load the items?
2) Is it a good idea to serialize() a recursive object like the one I’ve defined?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
SimpleXML 无法序列化,因为它被视为资源。但是,您可以轻松获取
$sx->toXML();
的输出并将其序列化,在反序列化后重新构造 SimpleXMLElement。重新解析 XML 的性能差异并不是很大,除非您使用的是非常大的 XML 树。
对于您的对象,您还可以实现
__sleep()
和__wakeup()
魔术方法,这将允许您分别在序列化和反序列化之前更改对象。序列化递归对象示例时,请勿将
$$items
变量包含在__sleep()
魔术方法中,并在__wakeup
中重新实现它>。SimpleXML cannot be serialized because it's considered to be a resource. However, you can easily grab the output of
$sx->toXML();
and serialize that, re-constructing the SimpleXMLElement(s) once you've unserialized them.The performance difference of re-parsing the XML is not very considerable unless you're working with extremely large XML trees.
In regards to your object, you can also implement the
__sleep()
and__wakeup()
magic methods that will allow you do alter the object before it is serialized and unserialized respectively.When serializing your recursive object example, don't include your
$$items
variable in the__sleep()
magic method and re-implement it in__wakeup
.