Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP simplexml_load_file case return false

I make unit test with phpunit (100% cover) for my PHP application and I have this :

$xml = simplexml_load_string($soapResponse); 
if (false === $xml) {
    throw new \Exception('invalid XML'); 
}

I don't find a test case with simplexml_load_string return false.

If you have a solution... Thanks

like image 981
V. Chataignier Avatar asked Apr 26 '26 18:04

V. Chataignier


2 Answers

as John C noted, invalid xml will cause simplexml_load_string to return false and generate warnings. Additionally you may want to disable those warnings and store them. To do so you can use libxml_use_internal_errors and libxml_get_errors.

<?php
$soapResponse = 'invalid_xml';
libxml_use_internal_errors(true);
$xml = simplexml_load_string($soapResponse);
if (false === $xml) {
    $errors = libxml_get_errors();
    echo 'Errors are '.var_export($errors, true);
    throw new \Exception('invalid XML');
}

So the output is:

array (
  0 => 
  LibXMLError::__set_state(array(
     'level' => 3,
     'code' => 4,
     'column' => 1,
     'message' => 'Start tag expected, \'<\' not found
',
     'file' => '',
     'line' => 1,
  )),
)

which may help you to identify problematic part in XML. This is extremely useful when XML is large.

like image 142
Jan Zdrazil Avatar answered Apr 29 '26 09:04

Jan Zdrazil


Any invalid XML will cause simplexml_load_string to return false:

$soapResponse = 'invalid';
$xml = simplexml_load_string($soapResponse); 
var_dump($xml);
// output: bool(false)

Note that this will also generate warnings.

like image 30
John C Avatar answered Apr 29 '26 09:04

John C