2015-04-03 111 views
1

我有一個javascript popup,「成功」使用PHP來加載另一個頁面作爲DOMDocument和「成功」通過ID找到一個元素來顯示它的文本使用nodeValue ...但是... nodeValue調用返回不是內部文本所需的元素,但是具有相同名稱的錨標記內的文本。下面是一些代碼:DOMDocument getelementbyid衝突?

的HTML和PHP這看似「作品」:

<span style="position:relative;"><span id="favelas" class="popup"> 

<?php 

// Create a new DOMDocument object 
$doc = new DOMDocument; 

// enable user error handling 
libxml_use_internal_errors(true); 

// Validate our document before referring to the id 
$doc->validateOnParse = true; 

// Load the key terms and identifications html file 
$doc->loadHtml(file_get_contents('http://teachers.dadeschools.net/jzoeller/APHG/0-Key-Terms-Identifications.html')); 

// Print in readable form the content the element by id 
print_r($doc->getElementById('favela')->nodeValue); 

?> 

</span><a href="javascript:void(null);" onMouseover="ShowPop('favelas');" onMouseout="HidePop('favelas');">favelas</a></span> 

現在,「應該」顯示是在上面的代碼中引用的頁面術語貧民窟的定義。我所得到的僅僅是「貧民窟」這個詞。

這裏的一些代碼,由PHP的頁面加載這個時候:

<tr> 
<td><a name="favela"> 
favela</a></td> 
<td class="def" id="favela">A shantytown or slum, especially in Brazil.</td> 
<td>07</td> 
<td>06</td> 
</tr> 

調試用的var_dump給了我這樣的:

對象(一個DOMElement)#1(17){[ 「tagName」] => string(1)「a」[「schemaTypeInfo」] => NULL [「nodeName」] => string(1)「a」[「nodeValue」] => string(8)「favela」 > [「nodeType」] => int(1)[「parentNode」] => string(22)「(對象值省略)」> [「childNodes」] => string(22) 「firstChild」] => string(22)>「(object value omitted)」[「lastChild」] => string(22)「(object value omit (22)「(對象值省略)」> [「previousSibling」] => NULL [「attributes」] => string(22) 「namespaceURI」] => NULL> [「prefix」] => string(0)「」[「localName」] => string(1)「a」[「baseURI」] => NULL> [「textContent」] = > string(8)「favela」}

這似乎是說它有一個名爲「favela」的錨,而不是名爲「favela」的td。是什麼賦予了?!

+0

這是爲什麼標記爲「Javascript」。這不是一個關於在PHP中實現的DOMDocument的PHP問題嗎? – jfriend00 2015-04-03 23:02:58

+0

我不知道DOMDocument,但我認爲它處理HTML爲_html40 loose_,並且那裏'a'元素的'name'屬性是一個ID屬性(ID屬性不需要名稱爲「id」 )。因爲你會發現'a'。 – 2015-04-03 23:11:48

+0

好吧,正如我懷疑的那樣,它在錨點上絆倒;那麼如何跳過錨點並獲得id的第二個實例,在這種情況下是「favela」。另外,謝謝你的解釋。我希望我的解決方案如此簡潔! – 2015-04-04 00:16:13

回答

1

您可以使用DOMXPath查詢,而不是getElementById()躲閃name屬性及與「貧民窟」的id屬性只針對元素:

$xpath = new DOMXPath($doc); 
$favelaElement = $xpath->query('//*[@id="favela"]')->item(0); 

print_r($favelaElement->nodeValue); 

輸出:

A shantytown or slum, especially in Brazil. 
+0

謝謝,我必須離開項目幾天......但您的解決方案的工作。只有一個小問題:我使用的編輯軟件似乎對使用引號非常敏感,所以我發現我必須用下面的代碼替換:('// * [@ id =「favela」]'): ( 「// * [@ id中= '貧民區']」)。 – 2015-04-09 12:58:47