简体   繁体   English

检查div ID是否存在(PHP)

[英]Check if div ID exists (PHP)

Is it possible to check if an element exists with PHP? 是否可以检查PHP是否存在某个元素?

I'm aware of the javascript method already but I just want to avoid it if possible. 我已经知道了javascript方法,但我只想尽可能避免它。

If you have the HTML server side in a string, you can use DOMDocument : 如果字符串中包含HTML服务器端,则可以使用DOMDocument

<?php
$html = '<html><body><div id="first"></div><div id="second"></div></body></html>';
$dom = new DOMDocument;
$dom->loadHTML($html);

$element = $dom->getElementById('second');
// this will be null if it isn't found
var_dump($element);

Not directly, because PHP is serverside only. 不直接,因为PHP仅在服务器端。

But if you really wish to do so, you may send the whole code of your page to a php script on your server using an ajax request, parse it there to find out if a div with a specified ID exists (see Shabbyrobes post; sure this would be very ineffective and is not recommended when you can easily check it with javascript...) and return the result in your ajax response. 但是,如果您确实希望这样做,则可以使用ajax请求将页面的整个代码发送到服务器上的php脚本,在那里进行解析以找出是否存在具有指定ID的div(请参阅Shabbyrobes帖子;请确保这将是非常无效的,不建议您使用javascript ...轻松检查它并在ajax响应中返回结果。

不可以。PHP只能提供内容,除了您要创建的内容之外,它没有DOM的控件或视图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM