簡體   English   中英

php中的Appendchild()錯誤

[英]Appendchild() error in php

我正在嘗試使用php向xml doc添加/插入數據,但我似乎得到了一個

“致命錯誤:在非對象上調用成員函數appendChild()。”

這是我的代碼的一部分,它不滿意的地方是:

$customer = $customers->item(0)->appendChild($customer);

function insertCustomer()
    {   

        try {
            $xmlFile = "../../data/customer.xml";
            $doc = DOMDocument::load($xmlFile);
            $doc->formatOutput = true;
            $customer = $doc->createElement('customer');

            $customers = $doc->getElementsByTagName("customers"); 


            $customer = $customers->item(0)->appendChild($customer);
            $newID = getLastId() + 1;
            $id = $doc->createElement('id');
            $idValue = $doc->createTextNode($newID);
            $id->appendChild($idValue);
            $customer->appendChild($id);


            $name1 = $doc->createElement('first_name');
            $nameValue = $doc->createTextNode($_GET["name"]);
            $value2 = $name1->appendChild($nameValue);
            $name = $customer->appendChild($name1);

            $name = $doc->createElement('surname');
            $nameValue = $doc->createTextNode($_GET["name"]);
            $value2 = $name->appendChild($nameValue);
            $name = $customer->appendChild($name);

            $name = $doc->createElement('password');
            $nameValue = $doc->createTextNode($_GET["password"]);
            $value2 = $name->appendChild($nameValue);
            $name = $customer->appendChild($name);


            $name = $doc->createElement('email');
            $nameValue = $doc->createTextNode($_GET["email"]);
            $value2 = $name->appendChild($nameValue);
            $name = $customer->appendChild($name);

            $name = $doc->createElement('phone');
            $nameValue = $doc->createTextNode($_GET["phone"]);
            $value2 = $name->appendChild($nameValue);
            $name = $customer->appendChild($name);

            $doc->save($xmlFile );
        } catch(Exception $e) { echo $e;} 
        echo "customer successfully registered and your new Id = ". $newID;
    }

您將獲得帶有$ customers = $ doc-> getElementsByTagName(“customers”)的xml節點; 但是返回值可以是null或沒有子項的空對象。 然后$ customers-> item(0)將為null引用。 所以“$ customers-> item(0) - > appendChild($ customer);”會導致空引用錯誤。 請檢查xml內容並添加條件命令,如果。 希望這對你有所幫助。 謝謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM