0

PHP Notice: Trying to get property of non-object in ...尝试 XPath 查询新创建的节点时,我总是收到该消息。

我的 XML 文件如下所示:

<products xmlns='http://example.com/products'>
    <product id='1'>
        <name>Product name</name>
    </product>
</products>

我的 PHP 文件本质上应用了一个 XPath 查询来获取现有的<product>和第二个查询<name>。这工作正常。

然后我将一个<product>带有子元素的新元素插入<name>到 DOM 根元素中,并尝试对新创建的元素进行第二个查询。获取属性工作正常,但是应该获取第一个 child<name>值的第二个查询失败并出现 PHP Notice Trying to get property of non-object in ...

$xmlFile = __DIR__ . '/products.xml';

$xml = new DOMDocument();
$xml->load($xmlFile);
$xml->formatOutput = true;

$xpath = new DOMXPath($xml);
$xpath->registerNamespace('p', $xml->lookupNamespaceUri($xml->namespaceURI));

/*
 * query the first product's ID and name
 */

$product1 = Product::$xpath->query("//p:product[@id=1]")->item(0);

$product1Id = $product1->attributes->getNamedItem('id')->nodeValue;
// => "1"
$product1Name = $xpath->query("p:name", $product1)->item(0)->nodeValue;
// => "Product name"

/*
 * create the second product
 */

$product2Node = $xml->createElement('product');
$product2Node->setAttribute('id', '2');

$product2NameNode = $xml->createElement('name', 'Test');
$product2Node->appendChild($product2NameNode);

$product2 = $xml->documentElement->appendChild($product2Node);

/*
 * query the second product's ID and name
 */

$product2Id = $product2->attributes->getNamedItem('id')->nodeValue;
// => "2"
$product2Name = $xpath->query("p:name", $product2)->item(0)->nodeValue;
// => PHP Notice:  Trying to get property of non-object in ...

$xml->save($xmlFile);

运行 PHP 文件后,XML 看起来正确:

<products xmlns='http://example.com/products'>
    <product id='1'>
        <name>Product name</name>
    </product>
    <product id='2'>
        <name>Test</name>
    </product>
</products>

我真的坚持这一点,我尝试在查询之前保存 XML,在保存后重新加载 XML,重新创建 XPath 对象等。

4

1 回答 1

1

我相信您需要使用该createElementNS功能(http://php.net/manual/en/domdocument.createelementns.php;您可能还想检查 setAttributeNS -- http://www.php.net/manual/en /domelement.setattributes.php ) 而不是createElement为了明确指出这些元素属于http://example.com/products命名空间。

$product2Node = $xml->createElementNS('http://example.com/products', 'product');
$product2Node->setAttribute('id', '2');

$product2NameNode = $xml->createElementNS('http://example.com/products', 'name', 'Test');
$product2Node->appendChild($product2NameNode);

(有点令人惊讶的是,在保存后重新加载 XML 并没有解决这个问题,但是如果没有看到尝试重新加载的代码,很难知道可能出了什么问题。)

于 2013-06-28T06:56:13.990 回答