[英]How do I use the PHP Simple HTML DOM Parser to parse this?
以下是我需要解析為PHP程序的HTML示例:
<div id="dump-list">
<div class="dump-row">
<div class="dump-location odd" data-jmapping="{id: 35, point: {lng: -73.00898601, lat: 41.71727402}, category: 'office'}">
<div class="SingleLinkNoTx">
<a href="#10" class="loc-link">Acme Software</a><br/><strong>John Doe, MBA</strong><br/>123 Main St.<br />New York, NY 10036<br /><strong class="telephone">(212) 555-1234</strong><br/>
</div><!-- END.SingleLinkNoTx -->
<a href="http://www.example.com" target="_blank" class="web_link">Visit Website</a><span><br />(0.3 miles)</span>
<div class="loc-info">
<div class="loc-info-text ">
John Doe, MBA<br /><a href="http://maps.google.com/?daddr=41.71727402,-73.00898601" target="_blank">Get Directions »</a>
</div>
</div>
</div>
這是我想從上面的HTML示例中提取到PHP中的信息:
lng: -73.00898601, lat: 41.71727402
category: 'office'
Acme Software
John Doe, MBA
123 Main St.
New York, NY 10036
(212) 555-1234
http://www.example.com
我已經嘗試過使用PHP Simple HTML DOM Parser,但我是新手,並且找不到與我需要做的相關的有效PHP示例。 我嘗試了一些像這樣的PHP代碼來理解它是如何工作的,但是var_dump($ e)產生了大量的輸出,並且在var_dump中有關於遞歸的消息。 所以我迷失了如何真正使用它。 非常感謝一些幫助!
$e = $html->find('.dump-location', 0)->find('.SingleLinkNoTx', 0);
echo $e;
var_dump($e);
使用XPath查找和提取HTML / XML文檔中的元素 - 特別是SimpleXMLElement :: xpath方法。
以下示例將找到某個位置的電話號碼:
$doc = new DOMDocument();
$doc->loadHTML('your html snippet goes here - or use loadHTMLFile()');
$xml = simplexml_import_dom($doc);
$elements = $xml->xpath('//*[contains(@class, "dump-location")]/div[@class="SingleLinkNoTx"]/strong[@class="telephone"]');
print_r($elements);
最復雜的部分是XPath表達式。 快速分解:
//
*[contains(@class, "dump-location")]
dump-location
類的任何元素 /
dump-location
父級的元素。 div[@class="SingleLinkNoTx"]
SingleLinkNoTx
類(並且沒有其他類名)的任何DIV
元素。 strong
STRONG
標記與telephone
類匹配的規則。 在問題中提供的HTML代碼段上使用此XPath表達式將導致輸出如下所示。 這很容易迭代並從中提取信息:
Array
(
[0] => SimpleXMLElement Object
(
[@attributes] => Array
(
[class] => telephone
)
[0] => (212) 555-1234
)
)
如果您知道文檔結構,則可以為要提取的每條信息構造XPath表達式。 或者,使用更通用的XPath表達式(例如,檢索所有dump-location
元素的表達式)並手動迭代元素可能更簡單。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.