1

I have the following XML file called 'cookie_domain.xml' with the contents:

<?xml version="1.0" encoding="UTF-8"?>
<setting>
    <parameter>cookie_domain</parameter>
    <displayname>Cookie Domain</displayname>
    <grouping>Sessions</grouping>
    <selecttype>text</selecttype>
    <setting />
    <help>Domain that the cookie is valid for</help>
</setting>

which I load into an object using:

$xml_object = simplexml_load_file('cookie_domain.xml');

The problem is that I want the 'setting' element to be null as specified in the XML, but what I get from the object, when I turn it into an array, is:

Array
(
    [parameter] => cookie_domain
    [displayname] => Cookie Domain
    [grouping] => Sessions
    [selecttype] => text
    [setting] => SimpleXMLElement Object
        (
        )

    [help] => Domain that the cookie is valid for
)

Is there anyway to get SimpleXML to honour the 'null' value instead of putting a 'SimpleXMLElement Object' in there? So I would end up with:

Array
(
    [parameter] => cookie_domain
    [displayname] => Cookie Domain
    [grouping] => Sessions
    [selecttype] => text
    [setting] => 
    [help] => Domain that the cookie is valid for
)

I am using this information to import into a database and the Object is causing issues as I need the element to be there, even if it is 'null' as this is valid in my application.

Thanks very much,

Russell

Russell Seymour
  • 1,333
  • 1
  • 16
  • 35
  • How (and why) are you turning it into an array? SimpleXML is *not* designed to parse XML into an array, it presents an array-like (and also object-like) API to the parsed XML. – IMSoP Aug 19 '13 at 10:51

1 Answers1

0

In XML, a self-closing element (e.g. <foo />) is equivalent to one with empty contents (e.g. <foo></foo>) so if you want this to translate as a php NULL value, you will have to check for the contents being an empty string.

A simple way of getting what you want given the example you've posted would be to loop over every element in the document setting an array key to the appropriate string, and replacing empty strings with NULL:

$settings_array = array();
foreach ( $xml_object->children() as $tag_name => $element )
{
    $settings_array[$tag_name] = trim( (string)$element );
    if ( strlen($settings_array[$tag_name]) == 0 )
    {
        $settings_array[$tag_name] = NULL;
    }
}

Here is a live demo.

IMSoP
  • 89,526
  • 13
  • 117
  • 169