[英]PHP XPath check if empty
我有这个PHP代码:
$document = new DOMDocument();
$document->loadHTML( $html );
$xpath = new DomXPath($document);
$tables = $xpath->query("//*[contains(@class, 'info')]");
$tableDom = new DomDocument();
$tableDom->appendChild($tableDom->importNode($tables->item(0), true));
如何检查$ tables变量是否包含我们可以在$ tableDom中使用的内容?
我尝试过:
if (!empty($tables)) {
echo("</br>not empty</br>");
} else {
echo("empty");
}
if (!$tablese) {
echo("empty</br>");
}
但是它总是说它不是空的,所有的HTML都不包含带有类信息的表。
试试这样
if ($tables->length>0) {
echo("</br>not empty</br>");
} else {
echo("empty");
}
The <Success /> element is an empty element, meaning it has no value. It is both, Start and End Tag.
You can test for existence of nodes with the XPath function boolean()
The boolean function converts its argument to a boolean as follows:
a number is true if and only if it is neither positive or negative zero nor NaN
a node-set is true if and only if it is non-empty
a string is true if and only if its length is non-zero
an object of a type other than the four basic types is converted to a boolean in a way that is dependent on that type
To do that with DOMXPath you need to use the DOMXPath::evaluate() method because it will return a typed result, in this case a boolean:
$xml = <<< XML
<OTA_PingRS>
<Success />
<EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;
$dom = new DOMDocument;
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$successNodeExists = $xpath->evaluate('boolean(/OTA_PingRS/Success)');
var_dump($successNodeExists); // true
demo
Of course, you can also just query for /OTA_PingRS/Success and see whether there are results in the returned DOMNodeList:
$xml = <<< XML
<OTA_PingRS>
<Success />
<EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;
$dom = new DOMDocument;
$dom->loadXml($xml);
$xpath = new DOMXPath($dom);
$successNodeList = $xpath->evaluate('/OTA_PingRS/Success');
var_dump($successNodeList->length);
demo
You can also use SimpleXML:
$xml = <<< XML
<OTA_PingRS>
<Success />
<EchoData>This is some test data</EchoData>
</OTA_PingRS>
XML;
$nodeCount = count(simplexml_load_string($xml)->xpath('/OTA_PingRS/Success'));
var_dump($nodeCount); // 1
@naga是对的。 DOMXpath::query()
总是返回的实例DOMNodelist
。 (或无效表达式的错误)。
如果表达式不匹配,您将收到一个空列表。 这是一个对象, empty()
将返回false
。
DOMNodeList::$length
包含列表中的节点数。 所以你可以验证它是一个条件:
if ($tables->length > 0) {
另一种方法是使用foreach()
。 您始终可以迭代节点列表。 如果您只想使用特定位置(第一个节点)中的节点,则可以在Xpath表达式中限制它。
$tables = $xpath->query("//*[contains(@class, 'info')][1]");
$tableDom = new DomDocument();
foreach ($tables as $table) {
$tableDom->appendChild($tableDom->importNode($table, true));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.