guest86
guest86

Reputation: 2956

PHP: Converting xml to array

I have an xml string. That xml string has to be converted into PHP array in order to be processed by other parts of software my team is working on. For xml -> array conversion i'm using something like this:

if(get_class($xmlString) != 'SimpleXMLElement') {
    $xml = simplexml_load_string($xmlString);
} 
if(!$xml) { 
    return false; 
} 

It works fine - most of the time :) The problem arises when my "xmlString" contains something like this:

<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>

Then, simplexml_load_string won't do it's job (and i know that's because of character "<"). As i can't influence any other part of the code (i can't open up a module that's generating XML string and tell it "encode special characters, please!") i need your suggestions on how to fix that problem BEFORE calling "simplexml_load_string".

Do you have some ideas? I've tried

str_replace("<","&lt;",$xmlString)

but, that simply ruins entire "xmlString"... :(

Upvotes: 0

Views: 125

Answers (1)

someOne
someOne

Reputation: 1675

Well, then you can just replace the special characters in the $xmlString to the HTML entity counterparts using htmlspecialchars() and preg_replace_callback().

I know this is not performance friendly, but it does the job :)

<?php
$xmlString = '<Line0 User="-5" ID="7436194"><Node0 Key="<1" Value="0"></Node0></Line0>';

$xmlString = preg_replace_callback('~(?:").*?(?:")~',
    function ($matches) {
        return htmlspecialchars($matches[0], ENT_NOQUOTES);
    },
    $xmlString
);

header('Content-Type: text/plain');
echo $xmlString; // you will see the special characters are converted to HTML entities :)

echo PHP_EOL . PHP_EOL; // tidy :)
$xmlobj = simplexml_load_string($xmlString);
var_dump($xmlobj);
?>

Upvotes: 2

Related Questions