XML验证错误:'找不到元素声明"example" '


XML Validation error: 'Can not find declaration of element "example".'

我正在使用PHP的SimpleXML对象从头开始创建XML文件。但是我在验证文档时得到这个错误:'找不到元素"example"的声明。'

下面是创建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>

任何帮助将不胜感激!由于

XML文件需要一些东西来验证它,文档类型定义(DTD)或XML模式。您没有提供任何验证,因此验证(即检查XML文档的结构/内容是否符合DTD/Schema中规定的规则)是不可能的。

或者您只是想检查格式是否良好(即,检查所有标签是否正确关闭,是否有非法字符等)?

为了验证XML文档,您需要DTD(或XML Schema)来描述有效文档的样子。您需要为您的XML应用程序编写DTD example.dtd,然后将其交给验证器,或者将其包含在您的XML文档中,方法是使用

作为前缀。
<!DOCTYPE example SYSTEM "example.dtd">

由于SimpleXML不支持文档类型,您必须手动在上面的行加上前缀,或者使用php的DOM扩展。幸运的是,您可以使用dom_import_simplexml将SimpleXML片段导入DOM。