DOMDocument :: getElementById返回NULL [英] DOMDocument::getElementById returns NULL

查看:60
本文介绍了DOMDocument :: getElementById返回NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

简化PHP DOM XML解析-如何?

这是我的XML(c.xml):

Here is my XML (c.xml):

<?xml version="1.0" encoding="utf-8"?>
<root>
    <head>
        <title id="title">Hello</title>
    </head>
</root>

我该做什么:

$dom = new DOMDocument;

$dom->load('./c.xml');

var_dump($dom->getElementById('title'));die(); // returns NULL

这里是什么问题?

UPD

$ dom-> validate(); 返回 DOMDocument :: validate():未找到DTD!

推荐答案

我认为手册解释了为什么会发生这种情况

I think The Manual explains why this may happen


为使此功能起作用,您将需要使用DOMElement-> setIdAttribute()设置一些ID属性,或者将DTD定义为ID类型的属性。在后一种情况下,在使用此功能之前,您需要使用DOMDocument-> validate()或DOMDocument-> validateOnParse来验证文档。

For this function to work, you will need either to set some ID attributes with DOMElement->setIdAttribute() or a DTD which defines an attribute to be of type ID. In the later case, you will need to validate your document with DOMDocument->validate() or DOMDocument->validateOnParse before using this function.

可能的解决方法:


  1. 调用 $ dom-> validate(); ,此后,您可以使用 $ dom-> getElementById(),而无论出于某种原因而出错。

  2. 使用XPath,如果您不想验证:

  1. Call $dom->validate();, afterwards you can use $dom->getElementById(), regardless of the errors for some reason.
  2. Use XPath if you don't feel like validating:

$ x = new DOMXPath($ dom);

$ el = $ x-> query( // * [@ id ='title'])-> item(0) ; //查找id = title

$el = $x->query("//*[@id='title']")->item(0); //Look for id=title

使用自定义DTD的示例:

Example of using a custom DTD:

$dtd = '<!ELEMENT note (to,from,heading,body)>
        <!ELEMENT to (#PCDATA)>
        <!ELEMENT from (#PCDATA)>
        <!ELEMENT heading (#PCDATA)>
        <!ELEMENT body (#PCDATA)>';

$systemId = 'data://text/plain;base64,'.base64_encode($dtd);

$creator = new DOMImplementation;
$doctype = $creator->createDocumentType($root, null, $systemId); //Based on your DTD from above

这篇关于DOMDocument :: getElementById返回NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆