【问题标题】:Unable to parse XML from string无法从字符串解析 XML
【发布时间】:2016-02-15 09:24:25
【问题描述】:

我正在尝试使用 https://github.com/orchestral/parser 将 XML 解析为数组,这是 Laravel 的 XML 文档解析器包。

当我尝试运行代码时,我收到一条错误消息:

Unable to parse XML from string.

下面是我试图解析为数组的 test.xml 文件。

<?xml version="1.0" encoding="utf-8"?>
<api>
<user followers="5">
<id>1</id>
<email>crynobone@gmail.com</email>
</user>
</api>

在我的 Controller 中,这就是我尝试解析 xml 文件的方式

public function index()
{

$xml = XmlParser::load('test.xml');
$user = $xml->parse([
'id' => ['uses' => 'user.id'],
'email' => ['uses' => 'user.email'],
'followers' => ['uses' => 'user::followers'],
]);

print_r($user);

}

有人知道为什么我无法将 xml 解析为数组吗?

【问题讨论】:

  • 您的代码看起来很像原始示例,不同之处在于您在第一行中有 xml 声明。你试过把它排除在外吗?
  • 鉴于如果simplexml_load_file 失败,Orchestra 似乎会抛出该异常,您是否绝对确定“test.xml”正在正确加载?它在正确的目录中吗?如果使用文件的完整路径会发生什么?
  • @igorshmigor 我试过省略 xml 声明,但它仍然给我同样的错误信息。
  • @MattGibson 你说得对,如果我使用完整路径,它就可以工作。谢谢。
  • 没问题。我已经发布了答案。

标签: php xml laravel-5


【解决方案1】:

XmlParser throws that error in the event of a basic failure in simplexml_load_file 与你传入的文件的路径。鉴于你没有指定文件的完整路径,我猜PHP的当前目录不是你的认为是,所以失败只是意味着解析器找不到文件。尝试使用文件的完整路径。

【讨论】:

    【解决方案2】:

    我遇到了同样的问题,但 Orchestral 没有在错误消息中提供有用的提示。

    由于它基于 SimpleXml,我尝试使用 SimpleXml 加载它,使用:

    <?php $xml=simplexml_load_file("your_filename_with_full_path.xml") or die("Error: Cannot create object"); print_r($xml); ?>

    这给了我信息

    parser error : Opening and ending tag mismatch: channel line 6 and item {"exception":"[object] (ErrorException(code: 0): simplexml_load_file(): file:/C:/.../storage/import/import.xml:242: parser error : Opening and ending tag mismatch: channel line 6 and item at ..........\\AbcController.php:24)

    嗯,更好地解释原因。

    然后我在修复 XML 后重试了 Orchestral,它立即工作。

    【讨论】:

      猜你喜欢
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-17
      • 1970-01-01
      相关资源
      最近更新 更多