Save/Alphabetize XML Foreach 数组中的响应

Save/Alphabetize XML Responses in a Foreach Array

我是 php 的新手,正在做这个项目是为了自学。

我正在从路透社 RSS 提要中导入 XML 数据,并希望按字母顺序对所有回复的内容进行排序。使用 foreach 循环将我想要的信息加载到页面时我没有遇到任何问题,但是我使用的排序系统将每个 xml 标题中的单词单独按字母顺序排列,而不是作为一个字符串一起排列。

如何将所有响应分组或保存在一起,以便在它们被 foreach 循环收集后作为一个整体进行排序?

这是我目前的情况:

<?php

function getFeed($feed_url) {

$content = file_get_contents($feed_url);
$x = new SimpleXmlElement($content);
$string = $x->channel->item ;

echo "<p>";

foreach($x->channel->item as $entry) {
    $string = $entry->title;
    $split=explode(" ", $string); 
    sort($split); // sorts the elements
    echo implode(" ", $split); //combine and print the elements 
}

echo "</p>";

}?>

考虑将标题保存到数组,对它们的值进行排序,然后迭代返回 echo 输出:

$content = file_get_contents("http://feeds.reuters.com/Reuters/PoliticsNews");
$x = new SimpleXmlElement($content);

$titles = [];
foreach($x->channel->item as $entry) {
    $titles[] = $entry->title;
}

sort($titles, SORT_NATURAL | SORT_FLAG_CASE);   # CASE INSENSITIVE SORT

foreach($titles as $t) {
    echo "<p>". $t ."</p>";
}

# <p>Ex-Illinois Governor Blagojevich's 14-year prison term upheld</p>
# <p>Exxon probe is unconstitutional, Republican prosecutors say</p>
# <p>Group sues Trump for repealing U.S. wildlife rule in rare legal challenge</p>
# <p>Indian techies, IT firms fret as Trump orders U.S. visa review</p>
# <p>Trump, Republicans face tricky task of averting U.S. government shutdown</p>
# <p>Trump administration may change rules that allow terror victims to immigrate to U.S.</p>
# <p>U.S. House committee sets more hearings in Trump-Russia probe</p>
# <p>U.S. judicial panel finds Texas hurt Latino vote with redrawn boundaries</p>
# <p>U.S. retailers bet on Congress over Bolivia to thwart Trump  border tax issue</p>
# <p>U.S. Treasury's Mnuchin: Trump to order reviews of financial rules</p>

您要做的是用所有单词构建一个数组,然后在最后对它进行排序。

<?php

function getFeed($feed_url) {    
    $content = file_get_contents($feed_url);
    $x = new SimpleXmlElement($content);
    $titles = "";
    foreach($x->channel->item as $entry) {
        $titles .= " $entry->title";
    }
    $split = explode(" ", $titles); 
    sort($split, SORT_FLAG_CASE | SORT_NATURAL);
    return trim(implode(" ", $split));
}

$words = getFeed("http://feeds.reuters.com/Reuters/PoliticsNews");

echo "<p>$words</p>";

我没有删除非单词字符,所以引号之类的东西会影响排序。

输出:

<p>'sanctuary' abuse after announcement, areas as battle California, cards, case crises cut detention drill Egyptian Egyptian-American Exxon financial Florida for freed from funding future give green greets healthcare Homeland hope in in in in Indian looms not of officials orders orders other permission plan possible prevent probe probes racial reboot reform resigns revamped review review review rule rules Russia Security see seeks senator sets slur state summons tax tax testify threatens to to to to Top Trump Trump Trump Trump Trump Trump-Russia Twitter U.S. U.S. U.S. U.S. Uphill visa-holders Waiting Washington will</p>