【问题标题】:PHP to get html source, then parse values within certain DIV tagsPHP 获取 html 源代码,然后解析某些 DIV 标记中的值
【发布时间】:2014-03-10 00:09:31
【问题描述】:

我可以很好地获取源代码,但我现在希望能够从特定 div 中获取数据:

$html = file_get_contents('http://www.website.com');

说 $html 包含:

<div class="productData">
   <div class="productDescription">Here is the product description</div>
   <div class="productPrice">1.99</div>
</div>

我希望能够返回 内的数据,并对所有出现的情况都执行此操作?

谢谢。

【问题讨论】:

    标签: php parsing html


    【解决方案1】:

    使用DOMDocument class,结合DOMXPath,类似这样:

    $url = 'http://www.website.com/';
    $dom = new DOMDocument();
    $dom->load($url);
    $xpath = new DOMXPath($dom);
    $nodes = $xpath->query("//*[contains(@class, 'productData')]");
    foreach ($nodes as $node) {
        // do something
    }
    

    【讨论】:

    • 要么执行此操作,要么使用preg_match 函数来匹配字符串并进行操作
    • 不,dont do that!
    • 我确实尝试了一些类似的方法,但我明白了:Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: Unexpected end tag : head in Entity
    • 如果使用修改后的代码会怎样(把$url改成你想用的)
    • 我得到:Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: htmlParseEntityRef: expecting ';' in Entity 这可能与包含 javascript 的页面有关吗?
    猜你喜欢
    • 2012-07-17
    • 2017-06-05
    • 1970-01-01
    • 2013-04-20
    • 2015-01-22
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多