Check out Scrivo

Do you want to try out Scrivo? Then here's a demo for you that does not just get your feet wet but lets you plunge right in.

Contact us

For more information, please contact us. We're happy to help you out!

Next Nov 4 Previous

Digesting messages

Consider the following script:

<?php
$str = <<<DATA
<?xml version="1.0" encoding="UTF-8"?>
<message>
<from>Marc</from>
<to>Judy</to>
<body>Yes, I've tweeted it too!</body>
</message>
DATA;

...

?>

What goes at the dots if we need to print the message body?

A: echo simplexml_load_string($str)->body;
B: echo simplexml_load_string($str)->message->body;
C: echo simplexml_load($str)->message->body;
D: echo simplexml_load_data($str)->body;

Answer

The correct function to create a SimpleXML object from a string is simplexml_load_string(). So answers C and D are false.

This function returns the root node which is in this case of type "message". Therefore you'll need to retrieve the body of the message directly from this object as given in answer A and not through a message member as in answer B.