0

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?

1
  • Why bother with XML? If your intent is simply to serialize the data, you can do all this in one line with JSON. Commented Feb 7, 2023 at 17:42

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.