2013-06-02 45 views
-1

如何僅返回PHP文件的主體? 的文件會是什麼樣子的例子:使用php返回頁面的某些部分

<html> 
<head> 
<title>Test Page</title> 
</head> 
<body> 
<div class="content"><p>Hello World</p></div> 
</body> 
</html> 

如何,我只用PHP返回頁面的主體?

<div class="content"><p>Hello World</p></div> 

我會用一個GET變量來表示我只需要body,否則需要整個頁面。

+1

你究竟想要做什麼?所以如果用戶點擊其中一個鏈接,它只會刪除正文,並添加新的頁面正文?你有沒有想過使用jQuery來代替它?我不認爲這是可能的PHP。我們在這裏說幾頁? – bob

+1

@lawnlanders這個想法是,當用戶點擊頁面上的鏈接,而不是使用jquery獲取整個頁面,標題和所有內容時,它只是獲取內容。 –

回答

1
<?php 
    // read and interpret your GET-input variable: 
    $body_only = isset($_GET['body_only']); // you can enhance/change this condition to match your needs 

    if(!$body_only) 
    { 
    // if NOT only body was requested, output intro (head, etc.): 
?> 
<html> 
<head> 
<title>Test Page</title> 
</head> 
<body> 
<?php 
    } 

    // always output body content: 
?> 
<div class="content"><p>Hello World</p></div> 
<?php 
    if(!$body_only) 
    { 
    // if NOT only body was requested, output outro: 
?> 
</body> 
</html> 
<?php 
    } 
?> 

就個人而言,我更喜歡在這種情況下,通常的C風格的語法(即<?php if(...) { ?> ... <?php } ?>),所以我上面使用它的代碼。 PHP還提供了一種語法,它可能會發現更容易閱讀:

<?php if (...): ?> 
    This will show if the expression is true. 
<?php else: ?> 
    Otherwise this will show. 
<?php endif; ?> 

Read this對從HTML PHP代碼的詳細信息。

另外,請考慮使用模板引擎。

0

PHP DOM你可以使用,它很簡單,並不需要任何解釋,但是如果你發現自己有麻煩不要擔心寫評論!