我正在尝试使用simple_xml_load_file解析XML文件,但出于某种原因,我只能在文件有多个记录时解析它!
这就是我要解析的内容:
object(SimpleXMLElement)#1 (1) {
["row"]=> object(SimpleXMLElement)#2 (1)
{ ["@attributes"]=> array(16)
{ ["ClientCode"]=> string(3) "259"
["Date"]=> string(23) "2013-08-20T02:29:00.273"
["Name"]=> string(16) "COMPLETE NAME"
["Contact"]=> string(0) ""
["Add1"]=> string(50) "ADDRESS LINE 1"
["Add2"]=> string(0) ""
["City"]=> string(3) "CITY"
["State"]=> string(0) ""
["ZipCode"]=> string(0) ""
["Country"]=> string(4) "COUNTRY"
["Email"]=> string(0) ""
["Phone1"]=> string(13) "PHONE NUMBER"
["Phone2"]=> string(0) ""
["Notas"]=> string(0) ""
["Destination"]=> string(7) "DESTINATION"
["Password"]=> string(0) "" }
}
}
我正在使用此代码执行此操作:
<?php
$xml = simplexml_load_file($data);
foreach($xml->NewDataSet->row[0]->row as $row) {
$client_id = $row['ClientCode'];
$fecha = $row['Date'];
$nombre = $row['Name'];
$direccion1 = $row['Add1'];
$direccion2 = $row['Add2'];
$ciudad = $row['City'];
$estado = $row['State'];
$pais = $row['Country'];
$email = $row['Email'];
$telefono1 = $row['Phone1'];
$telefono2 = $row['Phone2'];
$id1 = $row['ID1'];
$id2 = $row['ID2'];
echo 'These are the details'.$consignee_id.' '.$nombre.' '.$email.'<br>';
}
?>
$ data是保存在服务器上的文件,通常有很多记录。出于某种原因,当我尝试解析包含多个记录的文件时,会出现问题。我没有得到任何错误或任何东西,只是一个空白页面。我应该能够访问XML文件的每个字段(名称,客户端代码等)
我做错了什么?
谢谢!
答案 0 :(得分:1)
你必须得到<row>
的路径。
将转储转换为XML:
<NewDataSet>
<row
ClientCode = "259"
Date = "2013-08-20T02:29:00.273"
Name = "RafaelM"
/>
<row
ClientCode = "260"
Date = "2015-07-21T00:00:59:001"
Name = "MichelangeloX"
/>
</NewDataSet>
代码中的 $xml
代表XML的根元素,<row>
是其子代。因此,路径为$xml->row
:
$xml = simplexml_load_string($x); // assume XML in $x
foreach ($xml->row as $row) {
$id = $row["ClientCode"];
$created = $row["Date"];
$name = $row["Name"];
echo "client $name with the id $id has been created on $created." . PHP_EOL;
}
请在此处查看工作示例:https://eval.in/402313