PHP simplexml_load_file大小写返回false

时间:2016-01-07 09:05:05

标签: php phpunit simplexml simplexml-load-string

我使用phpunit(100%封面)为我的PHP应用程序进行单元测试,我有这个:

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

我找不到simplexml_load_string返回false的测试用例。

如果你有解决方案......谢谢

2 个答案:

答案 0 :(得分:3)

正如John C所指出的那样,无效的xml会导致simplexml_load_string返回false并生成警告。此外,您可能希望禁用这些警告并存储它们。为此,您可以使用libxml_use_internal_errors和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');
}

所以输出是:

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

可以帮助您识别XML中存在问题的部分。当XML很大时,这非常有用。

答案 1 :(得分:1)

任何无效的XML都会导致simplexml_load_string返回false

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

请注意,这也会产生警告。

相关问题