dongxi1680 2015-06-23 12:35
浏览 20
已采纳

在PHP中将当前页面上的H1元素废弃

I'm currently working with Wordpress. I have a hook that runs before a <title> attribute is populated with text that a user enters in the dashboard.

Now I want to set a default title of each page to equal an <h1> attribute text value on a current page. A fragment of the callback function for the hook I'm working with would look like:

if (!$seoTitle) {
    $seoTitle = '<....>';
}

return $seoTitle;

I want seoTitle to default to an <h1> element text on the current page. Is it doable? How can I achieve this?

  • 写回答

3条回答 默认 最新

  • dongzhuo5425 2015-06-23 14:20
    关注

    I'm not totally sure how you get your HTML but you could parse it with the built in DOM parser.

    <?php
    
    $html = "<!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>
    
    <h1>This is a Heading one</h1>
    <p>This is a paragraph.</p>
    <h1>This is a Heading two</h1>
    <p>This is a paragraph.</p>
    <h1>This is a Heading three</h1>
    <p><a href='testwww'> This is a paragraph.</a></p>
    
    
    </body>
    </html>";
    
    $dom = new DOMDocument();
    $dom->loadHTML($html);
    
    //If you want to get it from a website you could do the following:
    //$dom->loadHTML(file_get_contents('http://www.w3schools.com/'));
    
    // iterate through the html to get all h1 text
    foreach($dom->getElementsByTagName('h1') as $heading) {
        $h1 = $heading->nodeValue;
        echo $h1 . "<br>";
    }
    
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题