繁体   English   中英

从阵列创建 XML 馈送

[英]Creating XML Feed from Array

我遇到了一些从 RSS 提要过滤的数据生成 XML 的问题。

我已经能够将选举数据 t 转换为数组,但是在将数组转换为 XML 时我遗漏了一些东西。

我正在寻找类似的东西:

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

这是我的代码:

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

?>

问题似乎在于“foreach”区域。

任何帮助表示赞赏。

没关系,我想通了。

在 foreach 下,我这样做了(它是一个数组;不是 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();
        }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM