gpt4 book ai didi

Php 按日期排序多个 xmlDoc

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:20:15 26 4
gpt4 key购买 nike

我正在从 .XML 文件中提取博客页面列表,并打印网页的 2 个最新条目。但是,我不知道如何按 pubDatefile_edited 对 .XML 文件进行排序。

代码成功检索文件并打印两个最新条目。

这是检索文件并打印它们的 PHP 代码块。

<?php
date_default_timezone_set('Europe/Helsinki');

/* XML Source URL:s */
$pages=("blog/data/other/pages.xml");

/* XML Doc Conversions */
$xmlDoc = new DOMDocument();

echo "<div class='blog_article_wrapper'>";

function myFunction($x){
// Run 2 times, skip first file and stop loop.
for ($i=1; $i<=2; $i++) {

//Get "Title
$item_title=$x->item($i)->getElementsByTagName('title')
->item(0)->childNodes->item(0)->nodeValue;

//Get "Date" from .XML document.
$item_date=$x->item($i)->getElementsByTagName('pubDate')
->item(0)->childNodes->item(0)->nodeValue;

//Get "URL" from .XML document.
$item_url=$x->item($i)->getElementsByTagName('url')
->item(0)->childNodes->item(0)->nodeValue;

//Get "Author" from .XML document.
$item_author=$x->item($i)->getElementsByTagName('author')
->item(0)->childNodes->item(0)->nodeValue;

//Format date and author
$item_date = date('d.m.Y', strtotime($item_date));
$item_author = ucfirst(strtolower($item_author));

//Get content data from specifix .XML document being iterated in loop
$url=("blog/data/pages/" . $item_url . ".xml");
$xmlDoc = new DOMDocument();
$xmlDoc->load($url);
$y=$xmlDoc->getElementsByTagName('content')->item(0)->nodeValue;

//Limit content to 150 letters and first paragraph tag.
$start = strpos($y, '<p>="') + 9;
$length = strpos($y, '"</p>') - $start;
$src = substr($y, $start, $length);
$item_content = "\"" . (substr($src, 0, 150)) . "...\"";

// Page specific code for output comes here.
}
}

//Call loop and iterate data
$xmlDoc->load($pages);
$x=$xmlDoc->getElementsByTagName('item');
myFunction($x);
?>

任何指向正确方向的建议、代码或文章将不胜感激。

谢谢!

最佳答案

我自己用另一个 stackoverflow question 解决了这个问题和 php.net

//Directory where files are stored.
$folder = "blog/data/pages/";

$array = array();

//scandir and populate array with filename as key and filemtime as value.
foreach (scandir($folder) as $node) {
$nodePath = $folder . DIRECTORY_SEPARATOR . $node;

if (is_dir($nodePath)) continue;
$array[$nodePath] = filemtime($nodePath);
}

//Sort entry and store two newest files into $newest
arsort($array);
$newest = array_slice($array, 0, 2);

// $newest is now populated with name of .XML document as key and filemtime as value
// Use built in functions array_keys() and array_values() to access data

?>

我现在可以修改问题中的原始代码以仅使用这两个输出文件来检索所需数据。

关于Php 按日期排序多个 xmlDoc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34560272/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com