我花了一上午的时间进行研究,并在SO的帮助下,找到了如何使用Javascript获取元素的innerHTML。
这是为了填充搜索和社交开放图的元标签。这里有问题的标签是元描述标签。
我在Javascript中使用的是:
document.getElementsByClassName("report-description-text")[0].childNodes[2].nodeValue;
(有些尴尬的)html结构是这样的:
<!-- start report description -->
<div class="report-description-text">
<h5>Description</h5>
Welcome to Ushahidi. Please replace this report with a valid incident
<br/>
</div>
我想抓取文本"欢迎来到Ushahidi…"。但这个文本不在任何html标签中,它只是文本。上面的JS可以抓取文本。
然后我试图将其集成到PHP脚本中,但很快就被否决了,因为我现在知道,你不能在服务器端执行JS(我知道这一点,但从来没有足够的实践来真正实现它)。
PHP脚本如下:
if( strpos($url, '/reports/view') === 0 ) {
echo '<!-- Make this site discoverable, shareable and searchable -->
<meta name="description" content=[figure out what to put here]/>
// deal with these other metas later
<meta name="author" content="my name" />
在本例中,我希望内容的内容为:content="欢迎来到Ushahidi……"/>
使用PHP我该怎么做?它和JS一样简单吗?我做了一些研究,但只是弄糊涂了。
您必须了解PHP首先在服务器端运行,然后在客户端呈现Html。
你应该试着用另一种方式来面对这个问题。尝试以下方法:
在PHP中定义:
$description = "Welcome to Ushahidi. Please replace this report with a valid incident";
您可以在所有PHP代码中使用此变量:
echo '<!-- Make this site discoverable, shareable and searchable -->
<meta name="description" content=['.$description.']/>
// deal with these other metas later
<meta name="author" content="my name" />
然后在html上,您仍然可以使用这个变量,因为它已经设置好了:
<h5>Description</h5>
<?php echo $description; ?>
<br/>