【问题标题】:How to load several XML files into one string using simplexml_load_string?如何使用 simplexml_load_string 将多个 XML 文件加载到一个字符串中?
【发布时间】:2011-10-25 21:03:50
【问题描述】:

我想使用 simplexml_load_string 函数将三个 xml 文件加载到我的 php 文件中。

我怎样才能做到这一点?

@Jan-Henk:

这是我在 cmets 上写的:

这是我目前拥有的,它在一个 xml 文件中搜索员工 Jane:

$result   = simplexml_load_file('employees1.xml');
echo "<strong>Matching employees with name 'Jane'</strong><br />";
$employees = $result->xpath('/employees/employee[name="Jane"]');

foreach($employees as $employee) {
    echo "Found {$employee->name}<br />";
}
echo "<br />";

三个 xml 文件会是什么样子。然后不是像上面那样搜索员工简。它应该搜索三个文件中的重复项。因此,如果员工在三个文件中的任何一个中被列出两次。它应该返回:“找到简”。

【问题讨论】:

  • 尝试将它们转换为字符串,然后合并数组。

标签: php xml simplexml


【解决方案1】:

只需分别加载所有 3 个文件:

$xmlOne   = simplexml_load_file('path/to/file1.xml');
$xmlTwo   = simplexml_load_file('path/to/file2.xml');
$xmlThree = simplexml_load_file('path/to/file3.xml');

如果你真的想使用 simplexml_load_string 而不是 simplexml_load_file 你可以这样做:

$xmlOne = simplexml_load_string(file_get_contents('path/to/file1.xml'));

回答您的问题中的编辑,这仅适用于姓名 Jane:

$files = array('employees1.xml', 'employees2.xml', 'employees3.xml');
$xpathQuery = '/employees/employee[name="Jane"]';
$count = 0;

foreach ($files as $file) {
    $xml = simplexml_load_file($file);
    $result = $xml->xpath($xpathQuery);

    if (count($result) > 0) {
        $count++;
    }
}

if ($count > 1) {
    echo "Duplicates for Jane";
} else {
    echo "No duplicates for Jane";
}

【讨论】:

  • 我使用哪一个,simplexml_load_string 还是 simplexml_load_file 有关系吗? php 文件应加载三个 xml 文件。然后我使用这个guide 过滤所有三个文件的结果。
  • simplexml_load_file 一次做所有事情,所以这更容易。至于处理所有三个文件,您可以简单地执行要针对所有三个变量运行的代码。
  • “回答你的问题中的编辑,它只适用于简这个名字” - 我怎样才能让它适用于所有重复的。它应该搜索这三个文件,如果发现任何重复文件,它应该显示它们。发现重复......
  • 那么你应该先从三个XML文件中提取所有的名字,然后在循环中使用上面的代码来检查每个名字。但我不会为你写所有的代码,你应该自己努力。
  • 是的,我会的,感谢您抽出宝贵时间帮助我。我是新来的。而且我不希望你写所有的代码。但是,您能否指出正确的方向,即我应该搜索的位置或内容以学习从 XML 文件中提取所有名称。所以我可以使用你上面的代码。再次感谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-14
  • 2011-04-22
  • 1970-01-01
  • 1970-01-01
  • 2016-02-07
  • 1970-01-01
相关资源
最近更新 更多