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.

Data Model Questions /

How to import XML data in a dataobject?


Go to End
Reply


10 Posts   1772 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, 1798 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, 1798 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 [url=http://api.silverstripe.org/2.4/sapphire/filesystem/File.html#methodsetFilename]documentation of File[/url] 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