Using PHP to get DOM Element

后端 未结 2 1150
别跟我提以往
别跟我提以往 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:23

    You won't have access to the HTML if the redirect is from an external server. Let me put it this way: the DOM does not exist at the point you are trying to parse it. What you can do is pass the text to a DOM parser and then manipulate the elements that way. Or the better way would be to add it as another GET variable.

    EDIT: Are you also aware that the client can change the HTML and have it pass whatever they want? (Using a tool like Firebug)

    0 讨论(0)
  • 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'<br />";
        }
    }
    

    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'))
    
    0 讨论(0)
提交回复
热议问题