从XML文件中获取数据库插入的值

时间:2017-11-27 11:10:14

标签: php simplexml

我有以下格式的xml文件:

<?xml version="1.0"?>
<tryton>
<data skiptest="1" noupdate="1">
<record model="test.pathology.category" id="icdcat1">
<field name="name">I Certain infectious and parasitic diseases</field>
</record>

<record model="test.pathology.category" id="icdcat2">
<field name="name">II Neoplasms</field>
</record>

并进一步向下:

<record model="test.pathology.category" id="icdcat1-1">
<field name="name">(A00-A09) Intestinal infectious diseases</field>
<field name="parent" ref="icdcat1"></field>
</record>

<record model="test.pathology.category" id="icdcat2-6">
<field name="name">(C45-C49) Malignant neoplasms of mesothelial and soft tissue</field>
<field name="parent" ref="icdcat2"></field>
</record>
</data>
</tryton>

我尝试了以下内容:

<?php
if(file_exists('xml/myfile.xml'))
   {
$xml = simplexml_load_file('xml/myfile.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
}
print_r($xml);
?>

print_r给出以下值:

 SimpleXMLElement Object ( [data] => SimpleXMLElement Object ( [@attributes] => Array ( [skiptest] => 1 [noupdate] => 1 ) [comment] => SimpleXMLElement Object ( ) [record] => Array ( 
[0] => SimpleXMLElement Object ( [@attributes] => Array ( [model] => test.pathology.category [id] => icdcat1 ) [field] => I Certain infectious and parasitic diseases ) 
[1] => SimpleXMLElement Object ( [@attributes] => Array ( [model] => test.pathology.category [id] => icdcat2 ) [field] => II Neoplasms )

并进一步向下:

SimpleXMLElement Object ( [@attributes] => Array ( [model] => test.pathology.category [id] => icdcat1-1 ) [field] => Array ( 
[0] => (A00-A09) Intestinal infectious diseases 
[1] => SimpleXMLElement Object ( [@attributes] => Array ( [name] => parent [ref] => icdcat1 ) ) ) ) [23] => SimpleXMLElement Object ( [@attributes] => Array ( [model] => test.pathology.category [id] => icdcat1-2 )

我尝试过类似的事情:

foreach($xml->data->record[0]->attributes() as $a => $b) {
    echo $a,'="',$b,"\"\n";
}

我正在接受:

model="test.pathology.category" id="icdcat1" 

对于数据库中的插入,我需要以下内容: 从第1部分开始:

[id] => icdcat1 ) 
[field] => I Certain infectious and parasitic diseases 

,在第二部分:

id="icdcat1-1"
name = (A00-A09) Intestinal infectious diseases
ref="icdcat1" 2 etc...

因为我是新手程序员而感到困惑。请求帮助。

2 个答案:

答案 0 :(得分:1)

你应该能够简单地遍历记录元素......

foreach($xml->data->record as $record) {
    echo (string)$record['id']."/".(string)$record->field[0].PHP_EOL;
    if ( count($record->field) > 1 )    {
        echo $record->field[1]['ref'].PHP_EOL;
    }
}

使用[]访问属性(id),字段元素的值使用->

if部分检查是否有第二个字段值并从中提取ref元素。

使用示例文件,输出......

icdcat1/I Certain infectious and parasitic diseases
icdcat2/II Neoplasms
icdcat1-1/(A00-A09) Intestinal infectious diseases
icdcat1
icdcat2-6/(C45-C49) Malignant neoplasms of mesothelial and soft tissue
icdcat2

答案 1 :(得分:0)

请尝试这个

if(!$xml=simplexml_load_file('syntest.xml')){
trigger_error('Error reading XML file',E_USER_ERROR);
}



foreach ($xml as $syn) {
$w1 = $syn->w1;  
$w2 = $syn->w2;     
}