Deserialize xml for object with symfony2

I am collecting some xml data via the API and would like to deserialize it in a list of objects. I use Symfony2 and recognize the JMSSerializerBundle, but I really don't know how to use it.

I know that Sf2 allows you to serialize / deserialize an object to / from an array, but I'm looking for something more specific. For example, for this class:

class Screenshot
{
    /**
     * @var integer $id
     */
    private $id;

    /**
     * @var string $url_screenshot
     */
    private $url_screenshot;


    public function __construct($id, $url_screenshot) {
        $this->id = $id;
        $this->url_screenshot = $url_screenshot;
    }


    /**
     * Get id
     *
     * @return integer 
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set url_screenshot
     *
     * @param string $urlScreenshot
     */
    public function setUrlScreenshot($urlScreenshot)
    {
        $this->url_screenshot = $urlScreenshot;
    }

    /**
     * Get url_screenshot
     *
     * @return string 
     */
    public function getUrlScreenshot()
    {
        return $this->url_screenshot;
    }

    /**
     * Serializes the Screenshot object.
     *
     * @return string
     */
    public function serialize()
    {
        return serialize(array(
            $this->id,
            $this->url_screenshot
        ));
    }

    /**
     * Unserializes the Screenshot object.
     *
     * @param string $serialized
     */
    public function unserialize($serialized)
    {
        list(
            $this->id,
            $this->url_screenshot
        ) = unserialize($serialized);
    }

    public function __toString() {
        return "id: ".$this->id
              ."screenshot: ".$this->url_screenshot;
    }
}

I would like to serialize / deserialize to / from this kind of xml:

<?xml version="1.0" encoding="UTF-8" ?>
<screenshots>
   <screenshot>
      <id>1</id>
      <url_screenshot>screenshot_url1</url_screenshot>
   </screenshot>
   <screenshot>
      <id>2</id>
      <url_screenshot>screenshot_url2</url_screenshot>
   </screenshot>
   <screenshot>
      <id>3</id>
      <url_screenshot>screenshot_url3</url_screenshot>
   </screenshot>
</screenshots>

I really want to use something integrated / integrate in Sf2 (something "smooth") and prefer to avoid any home XML parsers.

+5
source share
1 answer

- XML , , . - → xml xml → object.

- , , , xml xml- .

( , xml) , ( ), , . plain serialize() unserialize() PHP . , .

: XML , simplexml : http://www.php.net/manual/en/function.simplexml-load-string.php

- .

: , simplexml_load_string() . SimpleXMLElement.

, simplexml .

2: . , . XML/YAML, , , . XML .

+4

All Articles