【问题标题】:Combine two XML PHP结合两个 XML PHP
【发布时间】:2012-05-24 01:28:34
【问题描述】:

我正在尝试合并两个或多个 xml 文件以便更好地使用。假设我有两个 XML 文件,我想在将它们的数据提取到表中之前组合它们的内容。

<table id="rounded-corner">
    <tr>
            <th>Title</th>
            <th>Download Link</th>
            <th>Language</th>
    </tr>


<?php

        $xml_request_url = 'file.xml';
        $xml = new SimpleXMLElement($xml_request_url, null, true);



        foreach ( $xml->results->content as $item )
        {

        echo "


<tr><td>" . $item->movie . "</td><td><a href=" . $item->download . ">Download Link</a>    </td><td>" . $item->language . "</td></tr>
";

}

        ?> </table>

你能给我举个例子吗?我不想为我拥有的每个 XML 文件制作表格。

<find>
<base>
http://www.example.com
</base>
<results items="2" itemsfound="2">
<song>
  <downloadlink>
  http://example.com/dldlink.php?lk=43543
  </downloadlink>
  <format>
  mp3
  </format>
</song>
<song>
  <downloadlink>
  http://example.com/dldlink.php?lk=87798
  </downloadlink>
  <format>
  mp4
  </format>
 </song>
 </results>
 </find>

【问题讨论】:

  • 查看其他post / 可能重复
  • 它们是简单的xml,格式相同但内容不同
  • @showerhead:这个问题还没有回答。但是我知道这个问题之前已经被问过和回答过,TS 应该真的使用搜索来寻找答案。
  • 你们为什么对这个问题投反对票?
  • 这不一样。另一篇文章是关于合并 xml 文件的,TS 想要在同一个表中显示来自 2 个 xml 文件的数据。有区别。

标签: php xml merge html-table


【解决方案1】:

您的问题实际上不是询问如何连接两个 XML 文件,而是更准确地说是如何从这两个文件中创建一个迭代器。这可以通过使用AppendIterator

<table id="rounded-corner">
    <tr>
            <th>Title</th>
            <th>Download Link</th>
            <th>Language</th>
    </tr>
<?php

    $content = new AppendIterator();
    $content->append(new IteratorIterator(simplexml_load_file('file1.xml')->results->content));
    $content->append(new IteratorIterator(simplexml_load_file('file2.xml')->results->content));
    foreach($content as $item)
    {
?>
    <tr>
        <td><?= $item->movie ?></td>
        <td><a href="<?= $item->download ?>">Download Link</a></td>
        <td><?= $item->language ?></td>
    </tr>
<?php
    }
?>
</table>

【讨论】:

  • 可捕获的致命错误:传递给 AppendIterator::append() 的参数 1 必须实现接口 Iterator,/home/ 中给出的 SimpleXMLElement 实例
  • 您能告诉我如何在您发布的代码上执行此操作吗?
  • @user1040157:当然,请参阅编辑。这样可行。确保从 XML 中选择正确的元素,这里的元素不是 XML 示例中的元素(验证标签名称)。
  • 如何用xpath查询结果?
  • @Mehmet 你可以先合并两个文件 - 或者 - 在两个文件上应用相同的 xpath 并从 xpath 结果创建迭代器(在 xpath() 返回值上使用 ArrayIterator,因为它返回数组)
【解决方案2】:

您可以将它们存储在中间数组中。例如:

$files = array('test1.xml','test2.xml');
$data = array();
foreach($files as $file)
{
 $xml = new SimpleXMLElement($xml_request_url, null, true);
 foreach($xml as $node)
   $data[] = $node;
}

然后使用您的 $data 数组获取所有值。

【讨论】:

    猜你喜欢
    • 2018-04-17
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    相关资源
    最近更新 更多