2014-05-22 107 views
0

我正在使用PHP簡單的HTML DOM解析器並且一直運行正常,直到獲取此div內容爲止。我已經嘗試了所有方法來獲取src屬性,找到一個標籤,img,並且都失敗了,我可以獲取img標籤,但只能獲得寬度,高度和alt attr(只是「some文本「出現,而不是其他字符串)。如何在此img標記中獲取src屬性

<img width="656" height="370" 
alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx"> 

我認爲問題出在alt attr上,所有帶。=符號的文本都會使解析器混淆。這個標籤會顯示在瀏覽器很好,所以,它必須是「標準」

編輯:

答案指出不能解決問題,我知道怎麼弄的SRC,問題是這個標籤。請花時間將其標記爲重複之前完整閱讀該問題。提供的答案中提供的代碼不適用於我展示的樣本。

$img_src = $element->src; 
if(!strstr($img_src, 'http://')) { 
    $img_src = $v . $img_src; 
} 

不從這個

<img width="656" height="370" 
    alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx"> 
+0

Parse dom ??? http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Gadonski

+0

這是撇號'是打破元素。我不知道如何解決它。 –

+0

可能獲取其父項的innerHTML,並搜索'src',或刪除撇號並將其​​作爲新(隱藏)元素追加並讀取其'src'。 (我假設解析器可以做到這一點。) –

回答

0

提取SRC ATTR的<img>元素無效HTML。它顯示了屬性聲明的幾個問題。我建議使用驗證服務,如W3C online validator以查看這些錯誤。我已將您的問題中的img標記包裝到this document進行驗證。

但是,雖然<img>標記無效,但DOMDocument類能夠解析它。就像這樣:

$string = <<<EOF 
<img width="656" height="370" 
alt="some text " .="" othertetx="" anothertext="" anothertext="" anothertext="" anothertext'="" title="same text in the alt attr " src="http://siteurl/getattach/somedir/somefile.aspx"> 
EOF; 

$doc = new DOMDocument(); 
@$doc->loadHTML($string); 

$images = $doc->getElementsByTagName('img'); 
echo $images->item(0)->getAttribute('src'); 

輸出:

http://siteurl/getattach/somedir/somefile.aspx 

注意,simplehtmldom類是沒有內建DOM擴展強大。它是在PHP沒有內置擴展的時候編寫的。在大多數情況下,它的使用現在可以被視爲不贊成使用。