XML SOAP保存到mySQL数据库

时间:2012-12-12 13:20:17

标签: php mysql xml codeigniter xml-parsing

我有一个XML文件

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
  <s:Header />
   <s:Body>
     <GetAllItemCategoryResponse xmlns="http://tempuri.org/">
       <GetAllItemCategoryResult xmlns:a="http://schemas.datacontract.org/2004/07/HQService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
         <a:ItemsCategory>
         <a:Code>prov</a:Code>
         <a:Description>Te Fresketa</a:Description>
         <a:LastModifiedDate>0001-01-01T00:00:00</a:LastModifiedDate>
         <a:active>true</a:active>
         </a:ItemsCategory>       
       </GetAllItemCategoryResult>
     </GetAllItemCategoryResponse>
   </s:Body>
 </s:Envelope>

我需要读取此文件并将记录存储到数据库中。 直到现在我已设法上传和读取记录,但我无法将它们存储在我的数据库中。我看过这个与我的案例有类似XML格式的例子,但它不起作用PHP - converting XML to array in PHP - parsing a soap xml in php and storing it in database

我正在使用CodeIgniter(下面是我的代码)

function set_xml()
{
    if ($this->input->post('submit'))
    {

        //uploading the file to the server
        if (!empty($_FILES['userfile']['name'])){
            $this->upload->do_upload($_FILES['userfile']['name']);
        }

    }

    $xml = realpath(APPPATH . '../public/').'/'.$_FILES['userfile']['name'];

    $fh = fopen($xml,'r');
    $theData = fread($fh,filesize($xml));
    fclose($fh);

            $element = new simpleXMLElement($theData);
    $centerElement = $element->Body->GetAllItemCategoryResponse->GetAllItemCategoryResult->ItemsCategory;

    $center = array(
        $centerElement->Code
    );

    var_dump($centerElement);

}

请帮忙吗?

1 个答案:

答案 0 :(得分:1)

您的问题是关于保存到数据库,还是访问XML中的元素?

我怀疑后者是这种情况,命名空间会让你失望。

请参阅以下示例,该示例访问SOAP响应中的元素:

$xml = file_get_contents(realpath(APPPATH . '../public/').'/'.$_FILES['userfile']['name']); 
$doc = simplexml_load_string($xml,NULL,false, "http://schemas.xmlsoap.org/soap/envelope/");
$doc->registerXPathNamespace('a', 'http://schemas.datacontract.org/2004/07/HQService');


foreach ($doc->xpath('//a:ItemsCategory') as $category) {
    foreach ($category->children('http://schemas.datacontract.org/2004/07/HQService') as $child) {
        echo $child->getName() . ":" . (string)$child . "\n";
    }
}

这输出以下内容:

Code:prov
Description:Te Fresketa
LastModifiedDate:0001-01-01T00:00:00
active:true

之后,只需保存到数据库即可。希望这有帮助!