Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Data Model Questions /

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

How to import XML data in a dataobject?


Go to End


10 Posts   4202 Views

Avatar
biapar

Forum Moderator, 435 Posts

4 August 2011 at 8:05pm

How to import XML data in a dataobject?

Avatar
swaiba

Forum Moderator, 1899 Posts

4 August 2011 at 9:05pm

Edited: 04/08/2011 9:05pm

how about...

$mytxml = file_get_contents ('my.xml');
$xml = simplexml_load_string($mytxml,null,LIBXML_NOCDATA);

foreach ($xml->MyNode as $node) {
	$do = new MyDataObject();
	$do->Field = $node->Field;
	$do->write();
}

Avatar
biapar

Forum Moderator, 435 Posts

4 August 2011 at 9:42pm

And..

How Do I import If a node have more child?

Avatar
swaiba

Forum Moderator, 1899 Posts

4 August 2011 at 9:53pm

if the $xml->Field is a list then do another foreach

Avatar
neglostyti

Community Member, 5 Posts

11 September 2011 at 11:06am

and what about images? I just have
public static $has_one = array( 'Photo' => 'Image' );

Avatar
kpower

Community Member, 7 Posts

11 September 2011 at 10:30pm

neglostyti,
Sorry I didn't understand what you really mean :) Does it has something to do with XML ?

Avatar
neglostyti

Community Member, 5 Posts

11 September 2011 at 10:33pm

let's pretend my xml structure is like:
<item>
<title>My title</title>
<pathToPicture>/images/image1.jpg</pathToPicture>
</item>

how I can import images to MyDataObject if there is public static $has_one = array( 'Photo' => 'Image' ); ?

Avatar
kpower

Community Member, 7 Posts

12 September 2011 at 12:01am

First thing is getting the file path from your XML document. Please follow the instructions given above and use simplexml to retrieve the file path. Once the file path is gotten, you can create an object of Image that represents the actual image in the retrieved path. If you have a look at the documentation of File you can see that Image class contains the inherited setFilename() method, which can be used to make that Image object to represent the image in the given location.

$img = new Image();
$img->setFilename($pathFromXML);
$img->Title = $titleFromXML;
$imgID = $img->write();

Then you can override the onBeforeWrite() method of your data object, obtain the image ID and add it to the has_one relation.

$myDataObject->PhotoID = $imgID;

Go to Top