2011-11-29 94 views
0

我使用PHP的SimpleXML對象從頭開始創建XML文件。但在驗證文檔時出現此錯誤:'無法找到元素聲明「示例」。「XML驗證錯誤:'無法找到元素聲明「示例」。「

下面是創建XML文檔代碼:

$xml = new SimpleXMLElement('<example></example>'); 
    $xml->addChild('producers'); 

    foreach($producers as $i=>$producer){ 
     $name = get_the_title($producer->ID); 
     $owner = get_post_meta($producer->ID, '_producer_contact_name', true); 
     $phone = get_post_meta($producer->ID, '_producer_phone', true); 
     $fax = get_post_meta($producer->ID, '_producer_fax', true); 
     $email = get_post_meta($producer->ID, '_producer_email', true); 
     $website = get_post_meta($producer->ID, '_producer_website', true); 
     $address = get_post_meta($producer->ID, '_producer_address', true); 

     $xml->producers->addChild('producer'); 
     $xml->producers->producer[$i]->addChild('name', $name); 
     $xml->producers->producer[$i]->addChild('owner', $owner); 
     $xml->producers->producer[$i]->addChild('phone', $phone); 
     $xml->producers->producer[$i]->addChild('fax', $fax); 
     $xml->producers->producer[$i]->addChild('email', $email); 
     $xml->producers->producer[$i]->addChild('website', $website); 
     $xml->producers->producer[$i]->addChild('civic', $address[0]); 
     $xml->producers->producer[$i]->addChild('mailing', $address[1]); 
     $xml->producers->producer[$i]->addChild('town', $address[2]); 
     $xml->producers->producer[$i]->addChild('province', $address[3]); 
     $xml->producers->producer[$i]->addChild('postal', $address[4]);   
    } 

    $open = fopen($file, 'w') or die ("File cannot be opened."); 
    fwrite($open, $xml->asXML()); 
    fclose($open); 

所產生的XML是這樣的:

<?xml version="1.0"?> 
    <example> 
     <producers> 
     <producer> 
      <name></name> 
      <phone></phone> 
      <fax></fax> 
      <email></email> 
      <website></website> 
      <civic></civic> 
      <mailing></mailing> 
      <town></town> 
      <province></province> 
      <postal></postal> 
     </producer> 
     </producers> 
    </example> 

任何幫助,將不勝感激!謝謝

+0

你如何驗證它? – Gordon

+0

可能重複[無法找到元素'作業'的聲明](http://stackoverflow.com/questions/1449797/cannot-find-the-declaration-of-element-assignments) – Gordon

回答

2

XML文件需要一些東西來驗證它,Document Type Definition (DTD)XML Schema。您不提供任何驗證(即檢查XML文檔的結構/內容是否符合DTD/Schema中規定的規則)是不可能的。

還是你只是想檢查well-formedness(即檢查所有標籤是否正確關閉,是否有任何非法字符等)?

+0

我現在明白了。我只想檢查格式,而且格式良好。謝謝。 – jasonaburton

+0

@jasonaburton那麼,使用驗證器來驗證格式良好。你目前如何驗證? – phihag

1

爲了驗證XML文檔,您需要一個描述有效文檔外觀如何的DTD(或XML Schema)。你需要寫一個DTD example.dtd爲XML的應用程序,要麼放棄它驗證或包括它在XML文檔中,通過與

<!DOCTYPE example SYSTEM "example.dtd"> 

前綴它,因爲SimpleXML的不支持的文檔類型,您必須手動前綴以上行或使用php的DOM擴展名。幸運的是,您可以使用dom_import_simplexml將SimpleXML片段導入DOM。

相關問題