Php按日期排序多个xmlDoc

时间:2016-01-01 21:32:39

标签: 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);
?>

非常感谢任何指向正确方向的建议,代码或文章。

谢谢!

1 个答案:

答案 0 :(得分:0)

我用另一个stackoverflow questionphp.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 

?>

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