Get inner html with php

2019-08-19 08:26发布

问题:

I started learning php and I came accross this issue. I have the html code in my form:

<label for="u">Usability <span id='u_score'>0</span> / 7</label>

I want to get the inner html of the span with id u_score. How do I do this in php? Any help would be appreciated.

I have already tried

$u_score = $_POST["u_score"];

but that returns undefined because there is no value associated with the span.

Thank you

回答1:

What you can do is to copy the span text content into a hidden input which will be posted:

<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
    function copySpanContent() {
    document.getElementById("u_score_value").value =
    document.getElementById("u_score").firstChild.data;
    }
</script>
</head>
<body>
<form method="POST" action="PHPSCRIPT.php" onsubmit="copySpanContent()">
<label for="u">Usability <span id='u_score'>0</span> / 7</label>
<input type="hidden" name="u_score_value" id="u_score_value">
<button type="submit">submit</button>
</form>
</body>
</html>

Then you can get the value from PHP with $_POST['u_score_value'].



回答2:

You can use Simple HTML DOM, it is an HTML parser for PHP. Download it then use this snippet:

include('simple_html_dom.php');
$html = file_get_html('yourHTMLfile.html');
$IDs = $html->find('span #u_score');
foreach($IDs as $id)
{
    echo $id.'<br />';
}

Hope this helps!



回答3:

php actually generates the html and does not perform any work (unless called via a method like ajax) to affect the page after it has completed building.

Javascript can get DOM element values, but PHP can not.

the method you are using will not work as the variable was not a $_POST variable but just an HTML element.



回答4:

Please learn the dividing line between client (Javascript) and server (PHP).

You could use PHP to deliver the HTML that you require.

You could also use Javascript to look at the DOM via getElementById to do the business.