如何在PHP中用HTML创建循环XML文件?

时间:2017-08-23 14:25:53

标签: php xml domdocument

我希望能够从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');
?>

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

1 个答案:

答案 0 :(得分: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);

    }
}