无法打印标题和网址的数组

时间:2019-07-06 15:19:42

标签: php arrays foreach

我不太擅长PHP。

我有一个.html文件的文件夹,该文件夹经常更改,然后我要搜索该文件夹,解析<h1>标签,然后打印/回显每个<h1>标签及其网址

使用某些Google搜索,从.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>";
        }

1 个答案:

答案 0 :(得分:2)

您正在将标题和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()