3

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

I'm aware of the javascript method already but I just want to avoid it if possible.

Daryl
  • 382
  • 3
  • 7
  • 19
  • 1
    What are your reasons for doing it server side? – Ash Burlaczenko Jan 04 '11 at 14:25
  • 1
    A what element? An HTML element in an HTML document? – Gumbo Jan 04 '11 at 14:25
  • Yes for example `
    ` if that doesn't exist `echo 'Test doesn't exist'`
    – Daryl Jan 04 '11 at 14:26
  • @Daryl where is the HTML document located? Are you loading it into PHP? – Pekka Jan 04 '11 at 14:27
  • 2
    you want to check out HTML parsers like the ones discussed here: http://stackoverflow.com/questions/3650125/how-to-parse-html-with-php In any event, it's generally best to avoid regexes for HTML. – dnagirl Jan 04 '11 at 14:27
  • possible duplicate of [Best Methods to parse HTML](http://stackoverflow.com/questions/3577641/best-methods-to-parse-html/3577662) – Gordon Jan 04 '11 at 14:31
  • @Ash Burlaczenko Well I'm trying to make this website as friendly as possible, meaning if some moron has JS switched off I don't want things to break too much. – Daryl Jan 04 '11 at 14:33

3 Answers3

8

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);
Shabbyrobe
  • 12,298
  • 15
  • 60
  • 87
0

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.

Thariama
  • 50,002
  • 13
  • 138
  • 166
-1

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

Matt Asbury
  • 5,644
  • 2
  • 21
  • 29
  • Yes php serves multiple classes to control a DOM. For instance lets say the DomDocument class. Not really perfect if it comes to html that is not good formatted but its there. – botenvouwer May 26 '13 at 11:06