Arkistos
Arkistos

Reputation: 1

Write a variable content in xml

Here is my problem: i want to put my variable (a SQL database serialized) in my xml file but only the 36 first characters are written. When I write all the text it works.

Here the code php:

public function createCache($coucou)
{
    $xml = new \DOMDocument;
    $xml->load(__DIR__.'/../../tmp/cache/datas/'.$this->typeData.'.xml');
    $xml->getElementsByTagName('content')->item(0)->textContent='';

    $text = serialize($coucou);

    $xml->getElementsByTagName('content')->item(0)->textContent=$text;


    $xml->save(__DIR__.'/../../tmp/cache/datas/'.$this->typeData.'.xml');
}

And my xml file :

<?xml version="1.0" encoding="utf-8"?>
<cache>
    <content>a:2:{i:0;O:11:"Entity\News":7:{s:9:"</content>
</cache>

For the information here is the value of $text

:a:2:{i:0;O:11:"Entity\News":7:{s:9:"*auteur";s:16:"LE grand manitou";s:8:"*titre";s:15:"C'est moiiiiiii";s:10:"*contenu";s:34:"ça fonctionnne!c'est genial!!!! ";s:12:"*dateAjout";s:19:"2018-08-25 11:19:11";s:12:"*dateModif";s:19:"2018-08-25 11:19:11";s:10:"*erreurs";a:0:{}s:5:"*id";s:1:"2";}i:1;O:11:"Entity\News":7:{s:9:"*auteur";s:6:"Pierre";s:8:"*titre";s:6:"Coucou";s:10:"*contenu";s:15:"Je fais un test";s:12:"*dateAjout";s:19:"2018-08-25 00:00:00";s:12:"*dateModif";s:19:"2018-08-25 00:00:00";s:10:"*erreurs";a:0:{}s:5:"*id";s:1:"1";}} 

Upvotes: 0

Views: 63

Answers (1)

Evert
Evert

Reputation: 99525

I'm about 80% certain this is your problem:

PHP's serialize() does not return ASCII or UTF-8 strings. It's a binary format, and you cannot embed it into text formats like XML or JSON. Don't do this.

The reason is that it uses things like 0x00 to denote certain things like private and protected properties.

I'm guessing that the DOM sees a non-ascii character and 'gives up'. You don't see it when you're outputting the string, because these bytes typically don't show up in browsers or terminals.

Using PHP's serialize() format is kind of a bad idea anyway... but since it kind of looks like you're using it as some caching mechanism on a filesystem, why would you embed it in XML? Just store the serialized string by itself. It's faster because you don't need an XML parser.

Upvotes: 1

Related Questions