简体   繁体   English

在PHP中,使用DomDocument getElementByID不起作用? 我究竟做错了什么?

[英]In PHP, using DomDocument getElementByID not working? What am I doing wrong?

Here is a bit of my code... 这是我的一些代码......

$dom = new DomDocument;
$html = $newIDs[0];
$dom->validateOnParse = true;
$dom->loadHTML($html);
$dom->preserveWhiteSpace = true;
$tryID = $dom->getElementById('ID');
echo $tryID;

I am trying to get multiple specific IDs from a website, this just shows one, and I have seen this method everywhere, including on here, but when I try and print something out nothing shows up. 我试图从一个网站获得多个特定的ID,这只是显示一个,我已经看到这个方法无处不在,包括在这里,但当我尝试打印出来时,没有任何东西出现。 I tried testing to see if it is reading something in with 我试过测试看它是否正在阅读

if(!$tryID)
{
    ("Element not found");
}

But it never prints that out either. 但它永远不会打印出来。 Lastly, I have used 最后,我用过

echo $tryID->nodeValue;

and still nothing... anyone know what I am doing wrong? 而且还没有......有谁知道我做错了什么?

Also, if I do get this working can I read in multiple different things to different variables on the same $dom ? 另外,如果我确实能够工作,我可以在同一个$ dom上读取不同变量的不同变量吗? If that makes ay sense. 如果这是有道理的。

Ok, so your solution. 好的,所以你的解决方案。

For a DIV: 对于DIV:

<div id="divID" name="notWorking">This is not working!</div>

This will do: 这样做:

<?php

    $dom = new DOMDocument("1.0", "utf-8");
    $dom->loadHTMLFile('YourFile.html');
    $div = $dom->getElementById('divID');

    echo $div->textContent;

    $div->setAttribute("name", "yesItWorks");
?>

Should work without the file as long as you pass a Well-Made XML or XHTML content, changing 只要你传递一个精心制作的XML或XHTML内容,就可以在没有文件的情况下工作

$dom->loadHTMLFile('YourFile.html');

to your 到你的

$dom->loadHTML($html);

Oh yeah, and of course, to CHANGE the content (For completeness): 哦是的,当然,改变内容(完整性):

$div->removeChild($div->firstChild);
$newText = new DOMText('Yes this works!');
$div->appendChild($newText);

Then you can just Echo it again or something. 然后你可以再次回声它或什么的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM