C
C
Craftist2015-08-05 10:38:38
PHP
Craftist, 2015-08-05 10:38:38

Translation from XML to PHP, how to pass data to array?

How to make XML turn into PHP array?
Let there be an XML file with program settings (a PHP DevelStudio program).
Let its content

<settings>
  <one type="gui" subtype="fullscreen">true</one>
  <two type="gui" subtype="alphablend">255</two>
</settings>

And you need to form it into an array like this:
Array
(
  [one] => Array
  (
    'type' => 'gui',
    'subtype' => 'fullscreen',
    'value' => 'true'
  )
  [two] => Array
  (
    'type' => 'gui',
    'subtype' => 'alphablend',
    'value' => '255'
  )
)

That is, so that the settings can be accessed like this:
c("Form1")->alphaBlendValue = $setting['two']['value'];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Mikhail Osher, 2015-08-05
@Craftist

$data = <<<XML
<settings>
  <one type="gui" subtype="fullscreen">true</one>
  <two type="gui" subtype="alphablend">255</two>
</settings>
XML;

function parse_xml($data)
{
    $result = [];
    $xml = simplexml_load_string($data);
    
    /** @var SimpleXMLElement $node */
    foreach ($xml as $key => $node) {
        $value = [];
        
        foreach ($node->attributes() as $k => $v) {
            $value[$k] = (string) $v;
        }
        
        $value['value'] = (string) $node;
        
        $result[$key] = $value;
    }
    
    return $result;
}

var_dump(parse_xml($data));

array(2) {
  'one' =>
  array(3) {
    'type' =>
    string(3) "gui"
    'subtype' =>
    string(10) "fullscreen"
    'value' =>
    string(4) "true"
  }
  'two' =>
  array(3) {
    'type' =>
    string(3) "gui"
    'subtype' =>
    string(10) "alphablend"
    'value' =>
    string(3) "255"
  }
}

D
Dmitry Kovalsky, 2015-08-05
@dmitryKovalskiy

Google for "XML to PHP array", "PHP XML deserialize" and more. The task is not at all unique, 100% is googled, and even on the toaster has already popped up.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question