检索与XPath和DOM文档元素(Retrieve elements with xpath and

2019-07-31 20:03发布

我有以下的HTML代码的广告清单。 我需要的是一个PHP循环获取每个广告如下因素元素:

  1. 广告网址(的href属性<a>标签)
  2. 广告图像URL(的src属性<img>标记)
  3. 广告标题(的html内容<div class="title">标签)
<div class="ads">
    <a href="http://path/to/ad/1">
        <div class="ad">
            <div class="image">
                <div class="wrapper">
                    <img src="http://path/to/ad/1/image.jpg">
                </div>
            </div>
            <div class="detail">
                <div class="title">Ad #1</div>
            </div>
        </div>
    </a>
    <a href="http://path/to/ad/2">
        <div class="ad">
            <div class="image">
                <div class="wrapper">
                    <img src="http://path/to/ad/2/image.jpg">
                </div>
            </div>
            <div class="detail">
                <div class="title">Ad #2</div>
            </div>
        </div>
    </a>
</div>

我设法与下面的PHP代码的广告网址。

$d = new DOMDocument();
$d->loadHTML($ads); // the variable $ads contains the HTML code above
$xpath = new DOMXPath($d);
$ls_ads = $xpath->query('//a');

foreach ($ls_ads as $ad) {
    $ad_url = $ad->getAttribute('href');
    print("AD URL : $ad_url");
}

但我没能拿到2个其他元素(图像URL和标题)。 任何的想法?

Answer 1:

我设法得到我需要的代码(基于奎武的代码):

$d = new DOMDocument();
$d->loadHTML($ads); // the variable $ads contains the HTML code above
$xpath = new DOMXPath($d);
$ls_ads = $xpath->query('//a');

foreach ($ls_ads as $ad) {
    // get ad url
    $ad_url = $ad->getAttribute('href');

    // set current ad object as new DOMDocument object so we can parse it
    $ad_Doc = new DOMDocument();
    $cloned = $ad->cloneNode(TRUE);
    $ad_Doc->appendChild($ad_Doc->importNode($cloned, True));
    $xpath = new DOMXPath($ad_Doc);

    // get ad title
    $ad_title_tag = $xpath->query("//div[@class='title']");
    $ad_title = trim($ad_title_tag->item(0)->nodeValue);

    // get ad image
    $ad_image_tag = $xpath->query("//img/@src");
    $ad_image = $ad_image_tag->item(0)->nodeValue;
}


Answer 2:

其他元素,你只是做了相同的:

foreach ($ls_ads as $ad) {
    $ad_url = $ad->getAttribute('href');
    print("AD URL : $ad_url");
    $ad_Doc = new DOMDocument();
    $ad_Doc->documentElement->appendChild($ad_Doc->importNode($ad));
    $xpath = new DOMXPath($ad_Doc);
    $img_src = $xpath->query("//img[@src]");
    $title = $xpath->query("//div[@class='title']");
}


文章来源: Retrieve elements with xpath and DOMDocument