DOMxpath query returns nothing

2019-09-14 17:50发布

问题:

I need to load, modify and output some 3rd party iframe on my webpage. As suggested, I had created the intermediary page that simply contains <iframe> with its src attribute.

The php code that outputs the page looks like this:

$iframe->loadHTML(file_get_contents("http://example.com/iframe_page.php")); //creating DOM object, see htm content below
$xpathObj= new DOMXPath($iframe);//creating DOMXPath object
foreach ($xpathObj->query('//div[@id="specific_id"]') as $node){ //this query returns nothing
    $node->parentNode->removeChild($node);//i need to remove the div with that id, but there is nothing to remove
}
echo $iframe->saveHTML($iframe->documentElement);//the iframe output works fine

And the content of my iframe looks something like this:

<html>
    <head>
    </head>
    <body>
        <div>
            <div>
                <div id="specific_id">
                </div>
            </div>
        </div>
    </body>
</html>

I've even tried disabling JS to see if this div is placed there by front-end code and nope with JS disabled the structure of the document looks exactly the same.

回答1:

The answer is rather simple. You CAN'T manipulate iframe element crossdomain using PHP DOMDocument.