我正在为搜索和打开图形创建元标记。
对于元描述标签,我想根据页面上两个html元素内容的串联动态设置值。
例如,如果这是我的html的片段:
<div class="report-description-text">
<h5>Description</h5>
Set of drawers
<br/>
该文件其他地方的另一个片段是:
<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函数的答案。
这是最简单的方法吗?我该怎么做?
答案 0 :(得分:2)
使用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);