使用PHP解析XML文件

时间:2017-10-31 19:15:20

标签: php xml xml-parsing

如何使用PHP解析下面格式化的XML文件?

我想将此XML文件中的数据存储到我的SQL数据库中,但是我在解析数据时遇到问题。

任何帮助都将不胜感激。

<?xml version="1.0" encoding="UTF-8" ?> 
<Data>
<Record>
  <Type>BUILDING</Type> 
  <Building_ID>0000_00</Building_ID> 
  <Facility_Name>0000</Facility_Name> 
  <Facility_Description /> 
  <Status /> 
  <Asset_Owner /> 
  <Address /> 
  <City /> 
  <State /> 
  <Zip /> 
  <Country /> 
  <Mailstops /> 
  <Site_Reference>ML01</Site_Reference> 
</Record>
<Record>
  <Type>SITE</Type> 
  <Building_ID>0001</Building_ID> 
  <Facility_Name>Olympic Base</Facility_Name> 
  <Facility_Description>N/A</Facility_Description> 
  <Status>OWNED</Status> 
  <Asset_Owner>SoCal</Asset_Owner> 
  <Address>N/A</Address> 
  <City>LOS_ANGELES</City> 
  <State>CA</State> 
  <Zip /> 
  <Country>USA</Country> 
  <Mailstops /> 
  <Site_Reference /> 
</Record>
</Data>

以下是我尝试过的无效代码:

$xmlurl = "http://myurl/data.xml";
$XMLDoc = simplexml_load_file("$xmlurl");

foreach($XMLDoc->Data->Record as $Record)
{
echo (string)$Record->Type;
    echo (string)$Record->Building_ID;
}

1 个答案:

答案 0 :(得分:1)

$XMLDoc的类型为SimpleXMLElement

我想你可以改变这一行:

foreach($XMLDoc->Data->Record as $Record)

到这一行:

foreach($XMLDoc->Record as $Record)

例如:

foreach($XMLDoc->Record as $Record)
{
    echo (string)$Record->Type;
    echo (string)$Record->Building_ID;
    echo "<br>";
}

将导致:

BUILDING0000_00
SITE0001