简体   繁体   中英

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 . 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

Fatal error: Call to a member function item() on a non-object in /home/s/public_html/import_xml.php on line 72

The error is because <image1> is missing from the XML.

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 = "";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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