使用 PHP DOMDocument 解析 XML
Parsing XML with PHP DOMDocument
我一直在四处寻找解决方案,但到处都找不到。
我正在尝试解析 XML
文件,但 XML
中缺少某些 TagNames
。一些帖子建议使用对象长度,但这也不起作用。
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
错误是因为 XML 中缺少 <image1>
。
关于修复的任何想法?
我就是这样做的。不确定它是否 "the best" 方式,但它有效...
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 = "";
}
我一直在四处寻找解决方案,但到处都找不到。
我正在尝试解析 XML
文件,但 XML
中缺少某些 TagNames
。一些帖子建议使用对象长度,但这也不起作用。
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
错误是因为 XML 中缺少 <image1>
。
关于修复的任何想法?
我就是这样做的。不确定它是否 "the best" 方式,但它有效...
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 = "";
}