简体   繁体   English

使用PHP DOMDocument解析XML

[英]Parsing XML with PHP DOMDocument

I've been looking around for a solution for this but can't find one anywhere. 我一直在寻找一种解决方案,但找不到任何解决方案。

I am trying to parse a XML file, but certain TagNames are missing from the XML . 我试图解析XML文件,但某些TagNames从缺XML Some posts suggest using the object length but this doesn't work either. 一些帖子建议使用对象长度,但这也不起作用。

if ($xmlObject->item($i)->getElementsByTagName('image1')->item(0)->childNodes->item(0)->length > 0) {
    $product_image1 = $xmlObject->item($i)->getElementsByTagName('image1')->item(0)->childNodes->item(0)->nodeValue;
} else {
    $product_image1 = "";
} 

Notice: Trying to get property of non-object in /home/s/public_html/import_xml.php on line 72 注意:尝试在第72行的/home/s/public_html/import_xml.php中获取非对象的属性

Fatal error: Call to a member function item() on a non-object in /home/s/public_html/import_xml.php on line 72 致命错误:在第72行的/home/s/public_html/import_xml.php中的非对象上调用成员函数item()

The error is because <image1> is missing from the XML. 该错误是因为XML中缺少<image1>

Any ideas on a fix? 有任何解决办法吗?

This is how I've done it. 这就是我所做的。 Not sure if its "the best" way, but it works... 不确定它的“最佳”方式,但是它可以工作...

foreach ($xmlDoc->getElementsByTagName('product')->item($i)->childNodes as $node) {
    if ($node->nodeType === XML_ELEMENT_NODE) {
        $nodes[] = $node->nodeName;
        echo "Processing node " . $node->nodeName . "<br />";
    }
}

if (in_array("name", $nodes)) {
    $product_name = $xmlObject->item($i)->getElementsByTagName('name')->item(0)->childNodes->item(0)->nodeValue;
} else {
    $product_name = "";
}

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

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