ds34222 2015-09-18 21:29
浏览 75
已采纳

使用PHP DOMDocument解析XML

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?

  • 写回答

1条回答 默认 最新

  • dongzhui4927 2015-09-18 22:41
    关注

    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 = "";
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵