Find and store all innerhtml of div to php variable

淺唱寂寞╮ 提交于 2019-12-12 04:18:56

问题


I’m trying to store the content of a div to a variable.

Example:

  <div class="anything">
    <p>We don't know the content of this div</p>
    </div>

I want to search for <div class="anything"> and store everything between opening and the end tag.

We also want to avoid using absolute pathnames, so that it only searches the current HTML/PHP file for this div where the code is present.

Is this possible with PHP, or is this only possible with JavaScript ?


回答1:


PHP is not that intelligent. He doesn't even know what he says.

PHP is a server-side language. It has absolutely NO clue about what the DOM (ie. what is displayed in your browser's window) is when it delivers a page. Yeah I know, PHP rendered the DOM, so how could it not know what's in there?

Simply put, let's say that PHP doesn't have a memory of what he renders. He just knows that at one particular moment, he is delivering strings of characters, but that's all. He kind of doesn't get the big picture. The big picture goes to the client and is called the DOM. The server (PHP) forgets it immediately as he's rendering it.

Like a red fish.

To do that, you need JavaScript (which is on the client's computer, and therefore has complete access to the rendered DOM), or if you want PHP to do this, you have to retrieve an full-rendered page first.

So the only way to do what you want to do in PHP is to get your page printed, and only then you can retrieve it with an http request and parse it with, in your case, a library such as simpleHtmlDom.

Quick example on how to parse a rendered page with simpleHtmlDom:

Let's say you know that your page will be available at http://mypage.com/mypage.php

$html = file_get_html('http://mypage.com/mypage.php');

foreach($html->find('div.anything') as $element) 
    echo $element->src . '<br>';



回答2:


you probably need a combination of those.

In your Javascript:

var content = document.getElementsByClassName("anything")[0].innerHTML();
document.getElementByID('formfield').value(content);
document.getElementByID('hiddenForm').submit();

In your HTML/PHP File:

<form id="hiddenForm" action="path/to/your/script">
<input type="hidden" name="formfield" value="" />
</form>

In the script you defined in the form action:

if(!empty($_POST)){
    $content = $_POST['formfield'];
    // DO something with the content;
}

Alternatively you could send the data via AJAX but I guess you are new to this stuff so you should start slowly :)

Cheers! steve



来源:https://stackoverflow.com/questions/21394363/find-and-store-all-innerhtml-of-div-to-php-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!