[英]PHP -> How can I check if a XML is empty
I get simple xml content from a request after a certain ID. 我从特定ID后的请求中获取简单的xml内容。 But sometimes an ID isn't anymore available and the XML is empty.
但有时ID不再可用,XML也是空的。
How can I check with PHP if a xml is empty? 如果xml为空,我如何检查PHP?
If someone has an idea I would appreciate if he could help me. 如果有人有想法我会很感激,如果他可以帮助我。
Thanks in advance. 提前致谢。
Marco 马尔科
If you can use SimpleXML extention: 如果您可以使用SimpleXML扩展:
$xmlObject = new SimpleXMLElement($xmlText);
if ($xmlObject->count() == 0) {
//it's empty
}
else {
//XML object has children
}
Also, SimpleXML is a very handy XML-reader/editor. 此外,SimpleXML是一个非常方便的XML阅读器/编辑器。
Details: http://ua2.php.net/manual/en/book.simplexml.php 详情: http : //ua2.php.net/manual/en/book.simplexml.php
I guess it depends on what you mean by empty, if the entire document is empty, you can check if the string version of the document is empty with: 我想这取决于你的意思是空,如果整个文档是空的,你可以检查文档的字符串版本是否为空:
if (empty($xmlString))
{
// is empty
}
But if you're expecting a root node, you might need to check if there are any children: 但是如果你期望一个根节点,你可能需要检查是否有任何子节点:
$xml = simplexml_load_file("test.xml");
if (empty($xml->getName()) && count($xml->children()) == 0) {
// is empty
}
Hope that helps. 希望有所帮助。
just use (string) before your id and it will work. 只需在你的id之前使用(字符串)它就可以了。 example:- your code is like this $id = $xml->mail->id;
例如: - 你的代码就像这个$ id = $ xml-> mail-> id;
then make it just like this $id = (string)$xml->mail->id; 然后就像这个$ id =(string)$ xml-> mail-> id;
it will work 它会工作
Just to add my two cents to an old question, but the top rated answer seems to suggest using simplexml_load_file("test.xml"); 只是将我的两分钱加到一个老问题上,但最受好评的答案似乎建议使用simplexml_load_file(“test.xml”); and then testing that a node you expect is not empty.
然后测试您期望的节点是否为空。 As this would thrown a warning level error if the file is empty, I would disagree and instead wrap the call with a test for filesize.
如果文件为空,这会抛出警告级别错误,我会不同意,而是用filesize测试来包装调用。
$xmlInfo = new SplFileInfo('test.xml');
if((int) $xmlInfo->getSize() > 0)
{
$xml = simplexml_load_file($xmlInfo->getPath());
}
Of course OP has asked How can I check with PHP if a xml is empty
, which doesn't specify if he means node or file, but for completeness there it is. 当然OP已经问过
How can I check with PHP if a xml is empty
, How can I check with PHP if a xml is empty
,这没有指明他是否意味着节点或文件,但是为了完整性,它是。
Try This: 试试这个:
$xml_str = '<?xml version="1.0" standalone="yes"?><Name/>';
$xml = new SimpleXMLElement($xml_str);
if(empty($xml->Name[0])){
// ITS EMPTY !! DO SOMETHING
echo "ITS EMPTY ASJK";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.