domdocument — PHP file_get_contents и эхо-измененные метатеги

Я отправляю URL с vars в php-скрипт и хочу, чтобы этот скрипт возвращал ту же html-страницу с измененными или созданными метатегами в соответствии с vars.
Все работает отлично, за исключением неизмененных тегов отображаются в теле вместо головы …

вот мой сценарий:

<?php
$imagetype = 'image/jpeg';
$panourl = $_GET["panourl"];
$snapshoturl = $_GET["snapshoturl"];
$vfw = $_GET["vfw"];
$vfh = $_GET["vfh"];
$pano_html = file_get_contents($panourl);

$html = new DOMDocument();
@$html->loadHTML($pano_html);
$meta_og_img = null;
$meta_og_img_type = null;
$meta_og_img_width = null;
$meta_og_img_height = null;
foreach($html->getElementsByTagName('meta') as $meta) {
if($meta->getAttribute('property')=='og:image'){
$meta_og_img = $meta->getAttribute('content');
}
if($meta->getAttribute('property')=='og:image:type'){
$meta_og_img_type = $meta->getAttribute('content');
}
if($meta->getAttribute('property')=='og:image:width'){
$meta_og_img_width = $meta->getAttribute('content');
}
if($meta->getAttribute('property')=='og:image:height'){
$meta_og_img_height = $meta->getAttribute('content');
}
}

if (is_null($meta_og_img)) {echo '<meta property="og:image" content="'.$snapshoturl.'"/>'; }
if (is_null($meta_og_img_type)) {echo '<meta property="og:image:type" content="'.$imagetype.'"/>'; }
if (is_null($meta_og_img_width)) {echo '<meta property="og:image:width" content="'.$vfw.'"/>'; }
if (is_null($meta_og_img_height)) {echo '<meta property="og:image:height" content="'.$vfh.'"/>'; }

$before = array($meta_og_img, $meta_og_img_type, $meta_og_img_width, $meta_og_img_height);
$after   = array($snapshoturl, $imagetype, $vfw, $vfh);

$pano_html = str_replace($before, $after, $pano_html);

echo $pano_html->saveHTML();
?>

Поэтому я загружаю html-страницу, проверяю, есть ли мета-свойства, а если нет, то создаю ее, а затем возвращаю html-страницу обратно.
Проблема в том, что в новом сгенерированном html все предыдущие метатеги помещаются в тело и не отображаются в голове …
Есть подсказка?
СПАСИБО !!!

0

Решение

Может быть проще использовать немного XPath, чтобы проверить, meta теги есть. Но главное, что просто echoИспользование новых тегов никак не влияет на их размещение в структуре документа.
Я сделал следующее: если теги не существуют, они создаются как элемент DOMele, добавляются атрибуты, а затем этот новый тег добавляется в начало head раздел.

Изменить: я обновил код, чтобы изменить метатег, если он существует, или добавить его, если он не существует.

<?php
error_reporting ( E_ALL );
ini_set ( 'display_errors', 1 );

$pano_html = <<< HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta property="og:image:type" />
<title>Insert title here</title>
</head>
<body>

</body>
</html>
HTML;
$snapshoturl = "http://someurl";

$html = new DOMDocument();
libxml_use_internal_errors(true);
$html->loadHTML($pano_html);
$xp = new DOMXPath($html);

$head = $html->getElementsByTagName("head")[0];
$ogImageMeta = $xp->query("//meta[@property='og:image']");
if ( $ogImageMeta->length == 0 )    {
$newTag = $html->createElement("meta");
$newTag->setAttribute("property", "og:image");
$newTag->setAttribute("content", $snapshoturl);
$head->insertBefore($newTag,$head->firstChild);
}
else    {
$ogImageMeta[0]->setAttribute("content", $snapshoturl);
}
echo $html->saveHTML();

Это устанавливает выход как

<!DOCTYPE html>
<html>
<head>
<meta property="og:image" content="http://someurl">
<meta charset="UTF-8">
<meta property="og:image:type">
<title>Insert title here</title>
</head>
<body>
</body>
</html>

Это делает только один тег, я надеюсь, что остальные будут достаточно легко скопировать из кода.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector