0

I have a string like this:

<enq fiscal="no" lastcommanderror="no" intransaction="no" lasttransactioncorrect="yes" />

I want to convert the above string into an array, and the output has to be this:

array(
    ['fiskal'] => "no",
    ['lastcommanderror'] => "no",
    ['intransaction'] => "no",
    ['lasttransactioncorrect'] => "yes"
)
1
  • Your string looks like part of an XML document, so you should be able to use a DOM parser. Commented Aug 12, 2019 at 16:21

3 Answers 3

2

You can use SimpleXMLElement:

$xmlString = '<enq fiscal="no" lastcommanderror="no" intransaction="no" lasttransactioncorrect="yes" />';

$array = ((array)(new SimpleXMLElement($xmlString)))["@attributes"];

var_dump($array);
Sign up to request clarification or add additional context in comments.

Comments

2

You could make the string a json by replacing some characters then json_decode it.

$str = str_replace(['<enq ',  ' />', '=', ' '], ['{"', '}', '":', ',"'], $str);

$arr = json_decode($str, true);

Comments

0

You can try this:

$string = '<enq fiscal="no" lastcommanderror="no" intransaction="no" 
lasttransactioncorrect="yes" />';

// remove the <enq /> and whitespaces
$string = trim(ltrim(rtrim($string, '/>'), '<enq'));

$finalArray = [];
foreach (explode(' ', $string) as $value) {
    $elements = explode('=', $value);
    $finalArray[$elements[0]] = $elements[1];
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.