【问题标题】:Grabbing inner html using php使用 php 抓取内部 html
【发布时间】:2014-04-05 18:58:14
【问题描述】:

我正在为搜索和打开图表创建元标记。

对于元描述标签,我想根据页面上两个 html 元素内容的串联动态设置值。

例如,如果这是我的 html 的 sn-p:

<div class="report-description-text">
            <h5>Description</h5>
            Set of drawers          
<br/>

文档其他地方的另一个sn-p是:

<p class="report-when-where">
            <span class="r_date">09:58 Apr 5 2014 </span>
            <span class="r_location">123 main St, Toronto, ON, Canada</span>
                    </p>

我希望我的元标记是:

echo '    
<meta name="description" content="Set of drawers at 123 main St, Toronto, ON, Canada" />

一般来说对 php 和代码并不陌生。我也在这个网站上做了一些研究,并找到了使用 DOMinnerHTML 和 foreach 函数的答案。

这是最简单的方法吗?我该怎么做?

【问题讨论】:

  • @CasimiretHippolyte 不确定您所说的“关联”是什么意思?描述值将是页面上两个 html 元素内容的串联。 “一套抽屉”+“123 Main St”
  • 页面上的html元素是否不止一对?

标签: php html innerhtml


【解决方案1】:

一种使用DOMDocument和XPath的方式:

$dom = new DOMDocument();
@$dom->loadHTML($html);

$xpath = new DOMXPath($dom);

$query = '//div[@class = "report-description-text"]/h5[.="Description"]'
       . '/following-sibling::text()[1]';
$description = trim($xpath->query($query)->item(0)->textContent);

$query = '//p[@class = "report-when-where"]/span[@class = "r_location"]/text()';
$location = trim($xpath->query($query)->item(0)->textContent);

$meta = $dom->createElement('meta');
$meta->setAttribute('name', 'Description');
$meta->setAttribute('content', $description . ' at ' . $location);

// only needed if the head tag doesn't exist
if (!$dom->getElementsByTagName('head')->item(0)):
    $head = $dom->createElement('head');
    $dom->getElementsByTagName('html')->item(0)->insertBefore($head,
        $dom->getElementsByTagName('body')->item(0));
endif;

$dom->getElementsByTagName('head')->item(0)->appendChild($meta);

$result = $dom->saveHTML(); // or saveXML if you want xhtml

echo htmlspecialchars($result);

【讨论】:

    猜你喜欢
    • 2015-01-12
    • 1970-01-01
    • 2011-04-26
    • 2011-12-21
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多