Using PHP to get DOM Element

后端 未结 2 1167
别跟我提以往
别跟我提以往 2020-11-29 06:35

I\'m struggling big time understanding how to use the DOMElement object in PHP. I found this code, but I\'m not really sure it\'s applicable to me:

$dom = n         


        
2条回答
  •  攒了一身酷
    2020-11-29 07:33

    getElementsByTagName returns you a list of elements, so first you need to loop through the elements, then through their attributes.

    $divs = $dom->getElementsByTagName('div');
    foreach ($divs as $div) {
        foreach ($div->attributes as $attr) {
          $name = $attr->nodeName;
          $value = $attr->nodeValue;
          echo "Attribute '$name' :: '$value'
    "; } }

    In your case, you said you needed a specific ID. Those are supposed to be unique, so to do that, you can use (note getElementById might not work unless you call $dom->validate() first):

    $div = $dom->getElementById('divID');
    

    Then to get your attribute:

    $attr = $div->getAttribute('customAttr');
    

    EDIT: $dom->loadHTML just reads the contents of the file, it doesn't execute them. index.php won't be ran this way. You might have to do something like:

    $dom->loadHTML(file_get_contents('http://localhost/index.php'))
    

提交回复
热议问题