【问题标题】:How can I replace an iframe on my HTML page with PHP in the background?如何在后台用 PHP 替换 HTML 页面上的 iframe?
【发布时间】:2022-01-02 07:50:23
【问题描述】:

我正在尝试创建一个显示特定 YouTube 搜索的最新结果的网站。使用 PHP 我可以成功调用 API 并获取我需要的视频 ID,但是我无法使用它来更新面向用户的 HTML 页面。我希望 PHP 脚本更新 HTML 文件本身,因此用户加载页面时已经嵌入了最新结果(或自上次运行脚本以来的最新结果,我打算每 15 分钟左右安排一次)。

这是 HTML (main.html),我正在尝试替换 iframe 中的 src 链接。它应该从这里开始:

<div id="videoembed">
<iframe width="697" height="392" src="https://www.youtube.com/embed/CZIINXhGDcs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

到这里:

<div id="videoembed">
<iframe width="697" height="392" src="https://www.youtube.com/embed/ElGoC3qFYRg" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

我现在不关心src以外的值

the answers to this question 之后,我尝试通过它的nodeValue 替换元素,但结果是我得到了一个与原始iframe 相同的test.html 文件,因此创建了一个文件但没有执行替换。 (我保存到test.html 用于测试目的,最终版本将简单地覆盖main.html):

///Turn the API response into a usable json
$response = json_encode($service->search->listSearch('snippet', $queryParams));

///get the videoId
preg_match('/(?<=videoId"\:")(.*)(?="})/', $response, $output_array);

///use the videoId to make an iframe called $output_embed
$embed1 = "<iframe width=\"697\" height=\"392\" src=\"https://www.youtube.com/embed/";
$embed2 = "\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>";
$output_embed = $embed1 . $output_array[0] . $embed2;

///create a document
$doc = new DOMDocument();

///load in the main page with the existing embedded video
$html = "main.html";
$doc->loadHTMLFile($html);

///grab the contents of the videoembed div and replace them with the contents of the $output_embed
$belement = $doc->getElementById('videoembed');
$oldString = $belement->nodeValue;
$newHTML = str_replace($oldString,$output_embed,$html);
$doc->saveHTMLFile("test.html");

我也尝试像 this answer 一样 preg_replacing 它,但我得到了与没有任何更改的新 test.html 文件相同的结果。

$doc = new DOMDocument();
$html = "main.html";
$doc->loadHTMLFile($html);
$html = preg_replace('/<iframe.*?<\/iframe>/', $output_embed, $html);
$doc->saveHTMLFile("test.html");

我想我在这里遗漏了一些基本的东西。我觉得我的代码只是没有与我需要的交互。每当我尝试打印出 nodevalue 或任何获取内容的方式时,我都会得到一个空白结果。对PHP不太熟悉(一般没有正式的编码培训),我想我可能对字符串或数组或某些变量的处理方式有误解。

这是我目前的解决方法(这很慢,因为用户必须得到current.html):

PHP:

///Turn the API response into a usable json
$response = json_encode($service->search->listSearch('snippet', $queryParams));

///get the videoId
preg_match('/(?<=videoId"\:")(.*)(?="})/', $response, $output_array);

///create a document
$doc = new DOMDocument();

///force a full iframe into it in 3 parts: before the videoId, videoId, and after the videoId
$doc->loadHTML("<iframe width=\"697\" height=\"392\" src=\"https://www.youtube.com/embed/" . $output_array[0] . "\" title=\"YouTube video player\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture\" allowfullscreen></iframe>");
$doc->saveHTMLfile("current.html");

HTML:

<div id="videoembed">
    <?php
    include 'current.html';
?>
</div>

它工作正常,但感觉比它可能的慢很多。

【问题讨论】:

    标签: php html iframe youtube-data-api youtube-iframe-api


    【解决方案1】:

    只需 AJAX 网址并替换 iframe

    在 php 结束时执行此操作

    header("content-type: application/json");    
    echo "{ \"youtubeID\": \"$videoId\" }";
    

    并且拥有

    document.getElementById('myForm').addEventListener('submit', function(e) {
      e.preventDefault(); // stop submission
    
      fetch(`/search.php?q=${encodeURIComponent(this.queryParams.value)}`)
        .then(response => response.json())
        .then(data => {
          if (data.youtubeID) {
            document.getElementById('videoembed').innerHTML = `<iframe width="697" height="392" src="https://www.youtube.com/embed/${data.youtubeID}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>`;
          }
        });
    });
    
    <form id="myForm">
      <input type="text" name="queryParams" />
    </form>
    
    <div id="videoembed">
      <iframe width="697" height="392" src="https://www.youtube.com/embed/CZIINXhGDcs" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
    </div>
    

    【讨论】:

    • 谢谢!我不超级关注这个(以前从未使用过 ajax),但我会尝试一下,让你知道它是如何进行的。表单的任何原因?
    • 我现在不知道你是怎么得到搜索参数的,所以我只是猜测
    猜你喜欢
    • 2019-11-06
    • 2014-01-08
    • 2011-08-18
    • 1970-01-01
    • 2017-08-14
    • 2021-09-02
    • 1970-01-01
    • 1970-01-01
    • 2013-01-18
    相关资源
    最近更新 更多