Search code examples
phpxmlsimplexml

PHP SimpleXML Optional Child Nodes


I'm trying to separate my child nodes according their children but I can't figure out how to validate whether the node has a value.

Here's my XML:

<?xml version="1.0"?>
<testcase>
 <steps>
 <step id="one">
    <command>gettitle</command>
 </step>
 <step id="two">
    <command>click</command>
    <parameter>id=searchByAddressSubmit</parameter>
 </step>
 </steps>
</testcase>

Here's my Code:

$testcase = new SimpleXMLElement($xml);
foreach($testcase->steps->step as $step) {
    echo $step->parameter;
    echo $step->command;    
    if(empty($step->parameter)) {
        echo $step>command;
    }
} 

The result should be:

gettitle

I've tried empty(), array_key_exists(), and is_null() but nothing seems to pick a missing value. Any ideas?


Solution

  • If it is indeed a typo and you are not getting any output, it just means you have an error on this line:

    echo $step>command;
    

    It should be ->.

    If you have turned on error reporting, it should have given an error message:

    Notice: Use of undefined constant command - assumed 'command' in

    This should be:

    // turn on error reporting on development
    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    
    $testcase = new SimpleXMLElement($xml);
    foreach($testcase->steps->step as $step) {   
        if(empty($step->parameter)) {
            echo $step->command; // fixed arrow operator
        }
    }
    

    Output