我擅长php。
我有一个.html文件的文件夹,该文件夹将经常更改,然后我想搜索文件夹,解析<h1>
标签,然后打印/回声每个<h1>
标签及其URL。
从.html文件中获取<h1>
标签非常容易,但是我似乎无法打印<h1>
标题及其相应URL的列表。
这是我到目前为止所拥有的:
$url_list = glob('posts/*.html'); // Searches for all files and folders in above directory that end in .html.
foreach ($url_list as $url) { // Creates an array of post URL's and title <h1> tags.
$post = new DOMDocument(); // Creates string to load blog post.
$post->loadHTMLFile($url); // Loads blog post into string $post from its URL.
$h1_tags = $post->getElementsByTagName('h1'); // Finds all <h1> tags.
$first_h1 = $h1_tags->item(0); // Gets value of first <h1> tag.
$title = $first_h1->nodeValue; // Sets $title to value of first <h1> tag.
if (!empty($title)) { // Will only run on files which have a date in their metadata.
$post_list[$url] = $title;
$post_list[$title] = $url;
}
}
sort($post_list); // Sorts list of posts in alphabetical order.
$num = 1;
foreach ($post_list as $title) { //
echo "<a href="{$url}"><h2>".($num++).". {$title} = {$url}</h2></a>";
}
您将标题和URL添加到同一列表中 - 但反转。如果您将数据构建为...
if (!empty($title)) { // Will only run on files which have a date in their metadata.
$post_list[$title] = $url;
}
所以这只会添加一次,然后像...
一样输出它 foreach ($post_list as $title => $url) { //
echo "<a href="{$url}"><h2>".($num++).". {$title} = {$url}</h2></a>";
}
编辑:将sort()
更改为asort()