像在PHP-DomDocument中一样,在PHP类SimpleXML中使用“ getElement(s)By”? [英] 'getElement(s)By' in the PHP class SimpleXML like in PHP-DomDocument?
问题描述
我已经使用DomDocument& SimpleXML,但服务器不支持DomDocument(仅SimpleXML)。现在,我正在重写它,但是SimpleXML中没有任何功能,例如 getElementsByTagName和 getElementById(我只需要这两个)。我在php.net&上搜索了很多内容google.com,但找不到一个。
I have made a application using DomDocument & SimpleXML, but the server doesn't support DomDocument (Only SimpleXML). Now I am rewriting it, but there aren't any functions in SimpleXML like "getElementsByTagName" and "getElementById" (I only need those 2). I have searched a lot on php.net & google.com, but can't find one.
我自己写的不是很好。那么,有人知道我的替代/功能/提示/脚本吗? :)
I am not that good to write my own. So, does anyone know a alternative/function/tip/script for me? :)
预先感谢。
推荐答案
如果使用SimpleXML,则很高兴不支持这些DOM方法,而是使用 SimpleXMLElement :: xpath()
方法。
Happily, if SimpleXML doesn't support those DOM-methods, it supports XPath, with the SimpleXMLElement::xpath()
method.
并按标记名称或id搜索使用XPath查询,应该不会太难。
我想像这样的查询应该可以解决问题:
And searching by tag name or id, with an XPath query, shouldn't be too hard.
I suppose queries like theses should do the trick :
- 通过id搜索:
/ / * [@ id ='VALUE']
- 通过标签名称搜索:
// TAG_NAME
- search by id :
//*[@id='VALUE']
- search by tag name :
//TAG_NAME
例如,使用XML的以下部分和代码来加载它:
For example, with the following portion of XML and code to load it :
$str = <<<STR
<xml>
<a id="plop">test id</a>
<b>hello</b>
<a>a again</a>
</xml>
STR;
$xml = simplexml_load_string($str);
您可以通过其 id = plop $找到一个元素c $ c>像这样:
$id = $xml->xpath("//*[@id='plop']");
var_dump($id);
并搜索所有< a>
带有以下标记的标签:
And search for all <a>
tags with that :
$as = $xml->xpath("//a");
var_dump($as);
输出将是以下内容:
array
0 =>
object(SimpleXMLElement)[2]
public '@attributes' =>
array
'id' => string 'plop' (length=4)
string 'test id' (length=7)
array
0 =>
object(SimpleXMLElement)[3]
public '@attributes' =>
array
'id' => string 'plop' (length=4)
string 'test id' (length=7)
1 =>
object(SimpleXMLElement)[4]
string 'a again' (length=7)
这篇关于像在PHP-DomDocument中一样,在PHP类SimpleXML中使用“ getElement(s)By”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!