2013-04-09 26 views
0

我有以下腳本片段。最初我沒有意識到使用getElementById,我需要包含createDocumentType,但現在我得到上面列出的錯誤。我在這裏做錯了什麼?提前致謝!調用未定義的方法DOMDocument :: createDocumentType()

... 
$result = curl_exec($ch); //contains some webpage i am grabbing remotely 

$dom = new DOMDocument(); 
$dom->createDocumentType('html', '-//W3C//DTD HTML 4.01 Transitional//EN', 'http://www.w3.org/TR/html4/loose.dtd'); 
$elements = $dom->loadHTML($result); 
$e = $elements->getElementById('1'); 
... 

編輯:額外的說明,我驗證了遠程頁面上的DOM是正確的。

+0

我從來不用'createDocumentType'。你確定'getElementById()'沒有它不起作用嗎?此外,從數字開始的ID在技術上是不允許的。 – 2013-04-09 03:55:33

+0

好吧,沒有'DOMDocument :: createDocumentType'這樣的東西。你從哪裏得到這個想法? – deceze 2013-04-09 03:55:54

回答

1

DOMDocument沒有名爲createDocumentType的方法,您可以在Manual中看到。該方法屬於DOMImplemetation class。它是這樣使用(從手動拍攝):

// Creates an instance of the DOMImplementation class 
$imp = new DOMImplementation; 

// Creates a DOMDocumentType instance 
$dtd = $imp->createDocumentType('graph', '', 'graph.dtd'); 

// Creates a DOMDocument instance 
$dom = $imp->createDocument("", "", $dtd); 

既然你想HTML裝入文件,你不需要指定的文檔類型,因爲它是從導入HTML確定。您只需要擁有一些id屬性,或者將其他屬性標識爲ID的DTD。這是HTML文件的一部分,而不是解析PHP代碼。

$dom = new DOMDocument(); 
$dom->loadHTML($result); 
$element = $dom->getElementById('my_id'); 

將完成這項工作。

+0

好吧,原來我使用$ dom = new DOMDocument();緊接着是getElementById。我從我的搜索中不能理解的是,如何指定我不控制內容的網頁的id屬性?你能提供一個使用我的代碼片段但減去createDocumentType的例子嗎?在此期間,我會嘗試你的方式。我最初在getELementById上遇到致命錯誤,並且搜索引導我到當前的解決方案... – Shawn 2013-04-09 04:00:15

+0

更改我的答案以包含一個工作示例。 – nibra 2013-04-09 04:08:48

+0

哇哦。所以那是我在上面那個螺紋版本之前的原始代碼。雖然我收到了一堆錯誤和警告。使用你的版本(我的原版),解決方案就像@ $ dom-> loadHTML($ result)一樣簡單;壓縮錯誤。 – Shawn 2013-04-09 04:18:38

相關問題