0

I would like to be able to create an XML file from some of the content of a html page. I have tried intensively but seem to miss something.

I have created two arrays, I have setup a DOMdocument and I have prepared to save an XML file on the server... I have tried to make tons of different foreach loops all over the place - but it won't work.

Here is my code:

<?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');
?>

I really like simplicity, thank you.

Pavel_K
  • 10,748
  • 13
  • 73
  • 186
McClaudLive
  • 53
  • 2
  • 8

1 Answers1

1

You need to add each item in one at a time rather than as an array, which is why I build the XML for each div tag rather than as a second pass. I've had to assume that your XML is structured the way I've done it, but this may help you.

$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
  • 56,122
  • 11
  • 43
  • 55