cinameng
cinameng

Reputation: 323

extract XML tag content with PHP

I have a PHP script that extracts data from an XML and so far it only looks for tag attributes. How can I also extract the tag content?

XML

<test name="Example 1">
<status status="FAIL" starttime="20200501 09:36:52.452" endtime="20200501 09:37:07.159" 
critical="yes">Setup failed:
Variable '${EMAIL_INPUT}' not found.</status>
</test>

PHP

foreach ($result->test as $result) {
                     
                    echo $result['name'], PHP_EOL;
                    $endtime = $result->status;
                    echo $endtime['starttime'], PHP_EOL;
                    echo $endtime['endtime'], PHP_EOL;
                    echo $endtime['status'], PHP_EOL;

}

What I need is the text in-between the tags:

"Setup failed:Variable '${EMAIL_INPUT}' not found."

Thanks

Upvotes: 0

Views: 37

Answers (1)

u_mulder
u_mulder

Reputation: 54796

To get the contents of a node you can just cast node to string:

// I changed to `as $test` 'cause `as $result` 
// overwrites initial `$result` variable
foreach ($result->test as $test) {
    $endtime = $test->status;
    $text = (string) $endtime;
    // Also `echo` will cast `$endtime` to string implicitly
    echo $text;
}

Upvotes: 1

Related Questions