[英]What's the easiest way to extract a piece of data from HTML in PHP?
我正在處理大部分無效HTML的一小部分,並且需要提取一小部分數據。 考慮到大多數“標記”都是無效的,因此我認為將所有內容都加載到DOM中並不是一個好選擇。 而且,對於這種簡單情況,似乎有很多開銷。
這是我擁有的標記的示例:
(a bunch of invalid markup here with unclosed tags, etc.)
<TD><span>Something (random text here)</span></TD>
(a bunch more invalid markup here with more unclosed tags.)
<TD><span>Something (random text here)</span></TD>
部分不會在文檔中的任何位置重復其本身,因此我相信使用簡單的正則表達式即可解決問題。
但是,我對正則表達式感到恐懼。
我應該使用正則表達式嗎? 有沒有更簡單的方法可以做到這一點? 如果可能的話,我只想提取Something之后的文本(此處為隨機文本)。
提前致謝!
編輯-
HTML的確切示例(我已經省略了之前的內容,這是供應商使用的無效標記。我認為,該示例與該示例無關):
<div class="FormTable">
<TABLE>
<TR>
<TD colspan="2">In order to proceed with login operation please
answer on the security question below</TD>
</TR>
<TR>
<TD colspan="2"> </TD>
</TR>
<TR>
<TD><label class="FormLabel">Security Question</label></TD>
<TD><span>What is your city of birth?</span></TD>
</TR>
<TR>
<TD><label class="FormLabel">Answer</label></TD>
<TD><INPUT name="securityAnswer" class="input" type="password" value=""></TD>
</TR>
</TABLE>
</div>
如果您確定打開和關閉span標簽在同一行上。 。 。
$ cat test.php
<?php
$subject = "(a bunch of invalid markup here with unclosed tags, etc.)
<TD><span>Something (random text here)</span></TD>
(a bunch more invalid markup here with more unclosed tags.)";
$pattern = '/<span>.*<\/span>/';
preg_match($pattern, $subject, $matches);
print_r($matches);
?>
$ php -f test.php
Array
(
[0] => <span>Something (random text here)</span>
)
如果您不確定span標記在同一行上,則可以將html視為文本文件,並將grep用作span標記。
$ grep '[</]span>' yourfile.html
在您的情況下,使用DOM分析器並不是最佳選擇。 我堅信您需要SAX解析器,它僅提取文檔的一部分並將適當的事件發送給處理程序。 此方法可以輕松解析損壞的文檔。
范例: http : //pear.php.net/package/XML_HTMLSax3 http://www.php.net/manual/en/example.xml-structure.php
嘗試使用DOMDOcument::loadHTML()
方法,該方法應該消除與HTML相關的任何驗證錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.