开发者

Check if div ID exists (PHP)

开发者 https://www.devze.com 2023-02-02 16:00 出处:网络
Is it possible to check if an element exists with PHP? I\'m aware of the javascrip开发者_Go百科t method already but I just want to avoid it if possible.If you have the HTML server side in a string, y

Is it possible to check if an element exists with PHP?

I'm aware of the javascrip开发者_Go百科t method already but I just want to avoid it if possible.


If you have the HTML server side in a string, you can use 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.

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.


No. PHP can only serve content, it has no control or view of the DOM except what you ask it to create.

0

精彩评论

暂无评论...
验证码 换一张
取 消