jjb
jjb

Reputation: 37

How to convert XML into array of objects in PHP?

I am trying to build a simple web app since I want to learn PHP.

I have this code:

// create objects
$object = new Post();
$object->name = 'Post no. 1';
$object->content = "My glorious content\nwritten in two lines!";
$object->fixed = 'True';
$object->picture = 'pathtoimg1.png';
$posts[] = $object;
$object = new Post();
$object->name = 'Post no. 2';
$object->content = 'Content.';
$object->fixed = 'False';
$object->picture = 'pathtoimg2.bmp';
$posts[] = $object;

// set xml
$postsXml = new SimpleXMLElement('<arrayOfPost></arrayOfPost>');
foreach($posts as $post){
    $element = $postsXml->addChild('post');
    $element->addChild('name', $post->name);
    $element->addChild('content', $post->content);
    $element->addChild('fixed', $post->fixed);
    $element->addChild('picture', $post->picture);
}

echo $postsXml->asXML();

It creates this XML:

$xmlString = '<?xml version="1.0"?>
<arrayOfPost><post><name>Post no. 1</name><content>My content
written in two lines!</content><fixed>True</fixed><picture>pathtoimg1.png</picture></post><post><name>Post no. 2</name><content>Content.</content><fixed>False</fixed><picture>pathtoimg2.bmp</picture></post></arrayOfPost>';

And that is the class I am using:

class Post {
  // Properties
  public $name;
  public $content;
  public $fixed;
  public $picture;
}

How can I parse the XML string to be an array of object "Post" again?

Upvotes: 0

Views: 42

Answers (1)

Javed Ali
Javed Ali

Reputation: 41

You can use SimpleXMLElement class simplexml_load_string method to parse the XML string into a SimpleXMLElement object, and then iterate over the post elements to recreate the Post objects:

$xml = simplexml_load_string($xmlString);
$posts = array();
foreach ($xml->post as $postXml) {
  $post = new Post();
  $post->name = (string) $postXml->name;
  $post->content = (string) $postXml->content;
  $post->fixed = (string) $postXml->fixed;
  $post->picture = (string) $postXml-> picture;
  $posts[] = $post;
}

Upvotes: 1

Related Questions