我是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>";
}?>
答案 0 :(得分:0)
考虑将标题保存到数组,对其值进行排序,然后迭代返回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>
答案 1 :(得分:0)
你想要做的是用所有单词构建一个数组,然后在最后对它进行排序。
<?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>