【问题标题】:How to create looped XML file from HTML in PHP?如何在 PHP 中从 HTML 创建循环的 XML 文件?
【发布时间】:2017-08-23 14:25:53
【问题描述】:

我希望能够从 html 页面的某些内容创建 XML 文件。我已经努力尝试,但似乎错过了一些东西。

我已经创建了两个数组,我已经设置了一个 DOM 文档,并且我已经准备在服务器上保存一个 XML 文件...我已经尝试在整个地方创建大量不同的 foreach 循环 - 但它不会工作.

这是我的代码:

<?php
$page = file_get_contents('http://www.halfmen.dk/!hmhb8/score.php');
$doc = new DOMDocument();
$doc->loadHTML($page);
$score = $doc->getElementsByTagName('div');

$keyarray = array();
$teamarray = array();

foreach ($score as $value) {
    if ($value->getAttribute('class') == 'xml') {
        $keyarray[] = $value->firstChild->nodeValue;
        $teamarray[] = $value->firstChild->nextSibling->nodeValue;
    }
}

print_r($keyarray);
print_r($teamarray);

$doc = new DOMDocument('1.0','utf-8');
$doc->formatOutput = true;

$droot = $doc->createElement('ROOT');
$droot = $doc->appendChild($droot);

$dsection = $doc->createElement('SECTION');
$dsection = $droot->appendChild($dsection);

$dkey = $doc->createElement('KEY');
$dkey = $dsection->appendChild($dkey);

$dteam = $doc->createElement('TEAM');
$dteam = $dsection->appendChild($dteam);

$dkeytext = $doc->createTextNode($keyarray);
$dkeytext = $dkey->appendChild($dkeytext);

$dteamtext = $doc->createTextNode($teamarray);
$dteamtext = $dteam->appendChild($dteamtext);

echo $doc->save('xml/test.xml');
?>

我真的很喜欢简单,谢谢。

【问题讨论】:

  • 你的问题是?
  • 您可能想阅读this answer,然后重新编写您的陈述以包含一个问题

标签: php xml domdocument


【解决方案1】:

您需要一次将每个项目添加到一个而不是作为一个数组,这就是为什么我为每个div 标记而不是作为第二遍构建 XML 的原因。我不得不假设您的 XML 是按照我的方式构建的,但这可能会对您有所帮助。

$page = file_get_contents('http://www.halfmen.dk/!hmhb8/score.php');
$doc = new DOMDocument();
$doc->loadHTML($page);
$score = $doc->getElementsByTagName('div');

$doc = new DOMDocument('1.0','utf-8');
$doc->formatOutput = true;

$droot = $doc->createElement('ROOT');
$droot = $doc->appendChild($droot);

foreach ($score as $value) {
    if ($value->getAttribute('class') == 'xml') {
        $dsection = $doc->createElement('SECTION');
        $dsection = $droot->appendChild($dsection);

        $dkey = $doc->createElement('KEY', $value->firstChild->nodeValue);
        $dkey = $dsection->appendChild($dkey);

        $dteam = $doc->createElement('TEAM', $value->firstChild->nextSibling->nodeValue);
        $dteam = $dsection->appendChild($dteam);

    }
}

【讨论】:

  • 优秀的 Nigel Ren。这是完美的。非常感谢你。 :o)
  • 如果在创建元素时可以在该点设置它的值,而不是必须创建文本节点,那么它也更短。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 2018-07-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-02
相关资源
最近更新 更多