Search code examples
phpxmlsimplexml

Cannot get to XML element with PHP


I am processing a long piece of XML with PHP. I'm trying to get to a particular value, but having an issue:

$diag_data = simplexml_load_file($diagnostics);

print_r($diag_data->category->category[2]->measure[3]);

Output:

SimpleXMLElement Object
(
    [name] => Memory
    [value-list] => SimpleXMLElement Object
        (
            [item] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [name] => allocated memory
                            [value] => 3,354 MB
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [name] => free memory
                            [value] => 2,165 MB
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [name] => maximum memory
                            [value] => 10,923 MB
                        )

                    [3] => SimpleXMLElement Object
                        (
                            [name] => total free memory
                            [value] => 9,734 MB
                        )

                )

        )

)

Then I try this:

print_r($diag_data->category->category[2]->measure[3]->value-list);

Output:

PHP Parse error:  syntax error, unexpected ')', expecting '(' in /var/www/html/xmltester.php on line 17

I don't get it, I've tried putting single and double quotes around value-list but nothing worked. I have also tried curly brackets. What am I doing wrong?


Solution

  • When the key name contains a hyphen you will need a special syntax {""} to access that property:

    print_r($diag_data->category->category[2]->measure[3]->{"value-list"});