Floyd Floyd - 1 year ago 191
PHP Question

Parse symfony xml config

I have a symfony xml-config and need to parse it.

<?xml version="1.0" encoding="UTF-8" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<parameter key="abcxyz" type="collection">
<parameter key="abc" type="collection">
<parameter key="a" type="string">a</parameter>
<parameter key="b" type="string">b</parameter>
<parameter key="c" type="constant">\My\Bundle\Type::TYPE_ABC</parameter>
<parameter key="xyz" type="collection">
<parameter key="x" type="string">x</parameter>
<parameter key="y" type="string">y</parameter>
<parameter key="z" type="constant">\My\Bundle\Type::TYPE_XYZ</parameter>

and I need to get the values "abc" and "xyz".
I tried to get it with

$simpleXml = simplexml_load_string(file_get_contents(__DIR__ . '/myConfig.xml');

but the result is empty...

cb0 cb0
Answer Source

Add a namespace to the xml element and change the xpath query like this:

$simpleXml->registerXPathNamespace("s", "http://symfony.com/schema/dic/services");

This will give the result that you want:

array (size=2)
  0 => 
      public '@attributes' => 
        array (size=1)
          'key' => string 'abc' (length=3)
  1 => 
      public '@attributes' => 
        array (size=1)
          'key' => string 'xyz' (length=3)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download