1

I am looking to get the tag of a specific element in php, and I think I can do that through preg_match, but I am not sure.

Essentially I have something like:

<label>Some Jazz</label>

What I would like to do is:

if tag = label then do something, else do something else.

The problem is getting the label part from the html tag. I did how ever find this answer. How ever your thoughts are welcome.

I failed to mention I do not want the "some jazz" I want to see if the tag is a label or not. - this is in reference to some answers where it gets me whats between the tags and not the tag it's self.

Community
  • 1
  • 1
TheWebs
  • 12,470
  • 30
  • 107
  • 211
  • For your reference, http://stackoverflow.com/questions/3404433/get-content-within-a-html-tag-using-php-and-replace-it-after-processing – Roger Ng Dec 04 '12 at 03:17
  • If the HTML gets more complicated, you may want to consider using XPath. See example [here](http://www.earthinfo.org/xpaths-with-php-by-example/) – Stanley Dec 04 '12 at 03:20
  • I would suggest using: http://php.net/manual/en/function.simplexml-load-string.php. – Matt Whipple Dec 04 '12 at 03:21

2 Answers2

0

I'm a fan of parsing with Simple HTML DOM

http://simplehtmldom.sourceforge.net/
shapeshifter
  • 2,967
  • 2
  • 25
  • 39
0

See if it is:

<?php

//External html or you can set this by string
$html = file_get_contents("http://example.com/"); 

//Parse html to object
$doc = new DOMDocument();
@$doc->loadHTML($html); //To prevent some html errors

//Labels
$labels = $doc->getElementsByTagName('label');

//For each label
for ($i = 0; $i < $labels->length; $i++) {

    $label = $labels->item($i);

    //Check label value
    if($label->nodeValue == 'something') {
        //Do something
    }
    else {
        //Do something
    }
}

?>
Fred Wuerges
  • 1,965
  • 2
  • 21
  • 42
  • this doesnt help as I don't care about the value, I care about the tag. – TheWebs Dec 04 '12 at 14:49
  • Ignoring the value part, is not what you're looking for? Through the script I posted an answer you can get the label tag. If you uploaded the html does not have a tag label method `getElementsByTagName` returns 0. – Fred Wuerges Dec 04 '12 at 15:27