2013-06-26 138 views
-3

我正在嘗試更改/更新dom中的一個我的頁面的元描述。所以我試着按照下面的方式,xpath查詢沒有給出結果

libxml_use_internal_errors(true); //I'm not sure this is helpful 
$xpath = new DOMXPath($dom); 
$name = 'desciption'; 
$query = '/html/head/meta[@name=\''.$name.'\']/@content'; 
$contents = $xpath->query($query); 
echo $contents->item(0)->value; //blank :(

在這裏,我無法獲取元描述的內容值。

  • 我檢查了htmlspecialchars($dom) &這似乎是正確的。
  • 我檢查了頁面的查看源&說明位於html-> head-> meta 標記(頁頭標記的pastebin)。

任何人都可以幫我解決這裏可能存在的問題嗎?我的查詢有什麼問題嗎?

+1

我想你應該串聯$名稱用雙引號,因爲它應該是'@ name =「description」',同時刪除name屬性中的斜線。 '$ query ='/ html/head/meta [@name ='。「$ name」。']/@ content';' –

+0

沒有運氣。用單引號和雙引號試過,仍然沒有輸出。這是我的查詢'/ html/head/meta [@ name =「description」]/@ content'。 – Rikesh

+2

你看過http://stackoverflow.com/questions/2907478/get-meta-description-tag-with-xpath – user20232359723568423357842364

回答

3

適用於我,當alue用雙引號引起來時,讓我們發佈一個示例,因爲它在評論中不明確。

我創建了一個文件html.html

<html> 
    <head> 
     <title></title> 
     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
     <meta name="description" content="some content"> 
    </head> 
    <body> 
     <div>TODO write content</div> 
    </body> 
</html> 

,然後一個PHP:

<?php 
$file = "html.html"; 
$dom = new DOMDocument(); 
$dom->loadHTMLFile($file); 
$xpath = new DOMXPath($dom); 
$name = 'description'; 
$query = '/html/head/meta[@name="'.$name.'"]/@content'; 
$contents = $xpath->query($query); 
echo $contents->item(0)->value; 
?> 

,輸出爲some content

您需要的第一雙的人後關閉單引號,所以他們會被保留在引用的字符串中,然後放置變量,開始引用並重新放置雙引號

編輯:

我用你的HTML從發佈網站:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<style type="text/css" media="screen"> 
<!-- 
#qm0 {position:relative;} 
        #qm0 a {display:block; white-space:nowrap; } 
        #qm0 div a {float:none;} 
        #qm0 div {visibility:hidden;position:absolute;} 
        #qm0 a {float: left; } 
--> 
</style> 
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"> 
<title>Product1 Name</title> 
<link href="n-defaultStyle.css" rel="stylesheet" type="text/css"> 
<meta http-equiv="pragma" content="no-cache"> 
<meta name="keywords" content=" Ilmfpnv, VrbfZgj, Fsikeprr Mluw"> 
<meta name="description" content="Beu Urb Hcsmihnurb cl c avlqclb ZtatcZq nrbc in unidrdpt cft mbvfp kj rmi isspulu. Uqwoiab in sf upq lkspuj jZ oed diirovs"> 
</head> 

,仍然有沒有問題,輸出:

Beu Urb Hcsmihnurb cl c avlqclb ZtatcZq nrbc in unidrdpt cft mbvfp kj rmi isspulu. Uqwoiab in sf upq lkspuj jZ oed diirovs