0

I'm running into a few issues generating XML from data filtered from a RSS feed.

I've been able to turn the election data t into an array, but I'm missing something in turning the array into XML.

I'm looking for something like:

<election>
<race>
<title>Governor</title>
<data>Name 500 23%</data>
</race>
</election>

Here's the code I have:

<?php

$races = array("Governor","1st District Representative in Congress","37th District State Senator","37th District State Senator","107th District Representative in State Legislature","108th District Representative in State Legislature","109th District Representative in State Legislature","110th District Representative in State Legislature");

function has_keywords($haystack, $wordlist)
{
  $found = false;
  foreach ($wordlist as $w)
  {
    if (stripos($haystack, $w) !== false) {
      $found = true;
      break;
    }
  }
  return $found;
}

$rss = simplexml_load_file("https://mielections.us/election/results/RSS/2022PRI_MI_CENR_SUMMARY.rss");
foreach ($rss->channel->item as $i)
{
  if (
      has_keywords($i->title, $races)
   || has_keywords($i->description, $races)
   || has_keywords($i->category, $races)
  )
  {
    $electionresults[] = array
    (
        "title" => $i->title,
        "description" => $i->description,
        "link" => $i->link
    );
  }
}

print_r($electionresults);

$xml = new XMLWriter();
$xml->openURI('election-results.xml');
$xml->setIndent(true);
$xml->setIndentString('    ');
$xml->startDocument('1.0', 'UTF-8');
    $xml->startElement('election');
        foreach ($electionresults as $race) {
            $xml->startElement('race');
                $xml->startElement(name);
                    $xml->text($race->title);
                $xml->endElement();
                $xml->startElement(data);
                    $xml->text($race->description);
                $xml->endElement();
            $xml->endElement();
        }
    $xml->endElement();
$xml->endDocument();
$xml->flush();
unset($xml);

?>

The problem seems to lie in the "foreach" area.

Any assistance is appreciated.

DRog
  • 17
  • 5

1 Answers1

0

Nevermind, I figured it out.

Under foreach, I did this instead (it's an array; not XML):

        foreach ($electionresults as $race) {
            $xml->startElement('race');
                $xml->startElement(name);
                    $xml->text($race['title'][0]);
                $xml->endElement();
                $xml->startElement(data);
                    $xml->text($race['description'][0]);
                $xml->endElement();
            $xml->endElement();
        }
DRog
  • 17
  • 5
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 03 '22 at 10:19