dousi4257
2011-09-13 09:15 阅读 40
已采纳

如何让PHP在显示页面之前操作HTML代码(复制/粘贴)

How to get PHP to manipulate HTML code (copy/paste) before sending to the browser.

I want to use PHP to get html code form inside h1 and paste it in h2. On server. Before page is send over to the browser.

e.g ;

<h1> Some HTML CODE </h1>
<h2> <!-- EMPTY --> </h2>

<?php 
   // $var1 = HTML CODE from inside of h1
   // Paste in $var1 inside h2
   // Display The Page
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    drh47606 drh47606 2011-09-13 09:17

    Edit: manipulating DOM before outputting through browser:

    <?php
    
    $my_html = '<div>
            <h1>This is a h1</h1>
            <h2>This is a h2</h2>
    </div>';
    
    $dom = new DOMDocument();
    $dom->loadHTML($my_html);
    
    $h1 = $dom->getElementsByTagName('h1')->item(0)->nodeValue;
    var_dump($h1); // "This is a h1"
    
    $dom->getElementsByTagName('h2')->item(0)->nodeValue = $h1;
    
    echo $dom->saveHTML();
    

    This is just an example. Read up on DOMDocument's documentation.


    Previous answer: You can't. PHP runs on the server side and javascript (thereby jQuery) on the client side. PHP doesn't know how to handle anything happening in the browser after the page has loaded.

    点赞 评论 复制链接分享
  • dtx63505 dtx63505 2011-09-13 09:24

    I think there's some kind of fundamental misunderstanding how PHP (and JS) works. PHP creates the HTML page, it doesn't know how the browser will render it and it can't go "back" to the already rendered page to make changes. (Yes, I know it's possible, but not the same way JavaScript on a browser would do it.)

    If you want to avoid coding the same thing twice you can use variables or functions. For example to have the same text in both h1 and h2:

    $content = "Hello World!";
    echo "<h1>$content</h1>";
    echo "<h2>$content</h2>";
    
    // output: <h1>Hello World!</h1><h2>Hello World!</h2>
    

    But if you want the page to change after it's been sent to the browser you have to use JavaScript.

    点赞 评论 复制链接分享

相关推荐