What is the purpose of SimpleXML in PHP?
A
To parse JSON data B
To parse and manipulate XML data easily C
To handle SQL databases D
To parse CSV files
Analysis & Theory
SimpleXML is used to parse, read, and manipulate XML data in PHP easily.
Which function is used to load an XML file into a SimpleXML object?
A
simplexml_connect() B
load_xml_file() C
simplexml_load_file() D
xml_file_read()
Analysis & Theory
`simplexml_load_file()` loads an XML file into a SimpleXML object for parsing.
What does `simplexml_load_string()` do?
A
Loads an XML file B
Loads XML data from a string C
Loads JSON data D
Parses a PHP file
Analysis & Theory
`simplexml_load_string()` parses XML data directly from a string instead of a file.
What is the output of this?
```
$xml = simplexml_load_string('<note><to>John</to></note>');
echo $xml->to;
```
A
John B
to C
note D
Error
Analysis & Theory
It outputs 'John' because `$xml->to` accesses the `<to>` element.
Which method is used to iterate through child elements of an XML node?
A
foreach loop B
for loop C
while loop D
array_map
Analysis & Theory
SimpleXML allows direct use of `foreach` to iterate through child elements.
What does this code do?
```
$xml = simplexml_load_file('data.xml');
foreach($xml->book as $book) {
echo $book->title;
}
```
A
Prints all book authors B
Prints all book titles C
Deletes the XML file D
Saves data to XML
Analysis & Theory
It prints the title of each `<book>` element in the XML file.
Which PHP function is used to convert a SimpleXML object back into XML string format?
A
xml_parse() B
json_encode() C
asXML() D
xml_convert()
Analysis & Theory
`asXML()` converts a SimpleXML object back into an XML string.
What happens if the XML file does not exist when using `simplexml_load_file()`?
A
The function creates a blank file B
Returns false and throws a warning C
Returns an empty string D
It continues without error
Analysis & Theory
It returns false and generates a warning if the file is not found.
How do you handle errors when parsing XML with SimpleXML?
A
Use try-catch (with Exception handling enabled) B
Ignore errors C
Use mysql_error() D
Use file_get_contents()
Analysis & Theory
You can use `libxml_use_internal_errors(true)` with try-catch to handle XML parsing errors gracefully.
What does this code output?
```
$xml = simplexml_load_string('<person><name>Mike</name></person>');
echo $xml->name;
```
A
Mike B
person C
name D
Error
Analysis & Theory
It outputs 'Mike' by accessing the `<name>` element within `<person>`.