Php 按日期排序多个 xmlDoc

标签 php xml algorithm xml-documentation

我正在从 .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/

相关文章:

php - 添加更新或删除 WooCommerce 运输订单项目

php - 减少 WP_List_Table 的表格宽度

java - 当 Camel 从 XML 文件加载路由时,在注册表中找不到 Bean

java - 显示方法不正常

algorithm - n 个对象的排列(重复排列)

java - 为什么我的不同排序算法会导致相同的运行时间?

php - 升级到 php 5.3.x 后 PDO 类未发现 fatal error

php - 执行 HTTP GET 请求而不等待响应

.net - SelectNodes 不在元素范围内

javascript - 如何计算不匹配的嵌套括号?