Tamara
Tamara

Reputation: 2980

Insert php SimpleXMLElement to the MongoDB

I'm using MongoDB(version 2.4.1) for storing information from XML files. During XML parsing process I create SimpleXMLElement for each item description. Here is the code for inserting new document:

$response = $collection->insert($object, array('safe'=>true, 'fsync'=> true)),

where $object has SimpleXMLElement type.

The problem is that I need to get id of the inserted document, but when I try to get it after insert operation it returns NULL:

$response = $collection->insert($object, array('safe'=>true, 'fsync'=> true)),
die(var_dump($object));

Is it an expected behavior for 'insert' operation?

Upvotes: 0

Views: 321

Answers (2)

Sammaye
Sammaye

Reputation: 43884

As you noted stdclass does work and the driver does successfully set the _id field on the object. This is because stdclass is analogous to an associative array and it's properties are able to be set publicly just like one.

SimpleXMLElement is not actually an object, as noted in the comments:

What makes SimpleXMLElement tricky to work with is that it feels and behaves like an object, but is actually a system RESOURCE, (specifically a libxml resource).

http://php.net/manual/en/class.simplexmlelement.php

Further on in the comment:

That's why you can't store a SimpleXMLElement to $_SESSION or perform straight comparison operations on node values without first casting them to some type of object. $_SESSION expects to store 'an object' and comparison operators expect to compare 2 'objects' and SimpleXMLElements are not objects.

As such with this in mind I believe you require to cast the SimpleXMLElement is an object, from a resource, before it will work. However, even with this it will be tricky for the driver to understand how exactly to insert the object if it is not a stdclass or something easily serializable.

Upvotes: 1

Philipp
Philipp

Reputation: 69703

You can generate your own MongoID for the _id field in the PHP code. When you create a new MongoID object, it uses the same algorithm the database would be using to generate an ID, so it isn't better or worse than letting mongodb generate it (only difference: the bytes 4-6 are the machine-identifier of the machine which runs the PHP stack, not the one which runs the database). But when you generate the _id In the PHP code, you have the advantage that it is known in PHP without having to query the database for the value it generated.

Upvotes: 0

Related Questions