给出以下XML:
<RegItems>
<RegItem Name="Test Regger" Email="me@here.com" OrgName="XXX">
<Establishment Est_Name="Test Org 1" Est_Addr="Test Org 1, 1 Acacia Ave, London, W12 8QT, UK" Est_ContactName="Test One" Est_ContactNum ="321321321" Est_EmailAdd = "test@here.com" />
<Screens>
<Timestamp time="Sun, 10 Feb 2019 00:05:24 GMT"/>
<Screen PDate="2019-01-19" EDate="2019-12-13" SModel="Xi75" Sno="750001" PCModSno="PC106-0001" PORef="444"/>
</Screens>
<UID hash ="dea31a69b70be709fb079bf7d50b1821"/>
</RegItem>
</RegItems>
我具有以下PHP代码来提取所有数据,但是在格式化的消息中,我为每个属性返回了空白。
$xml = new SimpleXMLElement($regXML);
var_dump ($xml);
$regName = $xml->xpath("/RegItem")['Name'];
$regEmail = $xml->xpath("/RegItem")['Email'];
$regOrgName = $xml->xpath("/RegItem")['OrgName'];
$regEstOrgName = $xml->xpath("/RegItem/Establishment")['Est_Name'];
$regEstOrgAddr = $xml->xpath("/RegItem/Establishment")['Est_Addr'];
$regEstOrgContact = $xml->xpath("/RegItem/Establishment")['Est_ContactName'];
$regEstOrgTel = $xml->xpath("/RegItem/Establishment")['Est_ContactNum'];
$regEstOrgEmail = $xml->xpath("/RegItem/Establishment")['Est_EmailAdd'];
$regTimeStamp = $xml->xpath("/RegItem/Timestamp")['time'];
$mesg = <<<EOF
=====================================================
Origin XML: $regXML
=====================================================
Registered By Details:
Name: $regName
Email: $regEmail
Organistion: $regOrgName
Registered Organisation:
Name: $regOrgName
Address: $regEstOrgAddr
Contact Name: $regEstOrgContact
Contact Tel: $regEstOrgTel
Contact Email: $regEstOrgEmail
Time: $regTimeStamp
=====================================================
Screens:
EOF;
$screens = $xml->xpath("/RegItem/Screens/Screen");
foreach($screens as $screen)
{
$screenWarrStartDate = $screen['PDate'];
$screenWarrEndDate = $screen['EDate'];
$screenModel = $screen['SModel'];
$screenSerial = $screen['Sno'];
$screenPCSerial = $screen['PCModSno'];
$screenPORef = $screen['PORef'];
$mesg .= <<< EOF
Screen Model: $screenModel
Screen Serial No: $screenSerial
PC Mod Serial No: $screenPCSerial
PO Ref: $screenPORef
Warranty Start: $screenWarrStartDate
Warranty End: $screenWarrEndDate
EOF;
}
$mesg .= "
=====================================================
";
return ( $mesg );
例如代替
Name: Test Regger
Email: me@here.com
Organistion: XXX
我得到:
Name:
Email:
Organistion:
答案 0 :(得分:2)
您的代码有几个问题。首先,xpath
返回一个元素数组,因此要访问一个单独的值,您需要提供一个数组索引。在您的情况下,由于只有一个RegItem
,因此可以只使用[0]
。其次,RegItem
不是XML中的顶级元素,因此XPath /RegItem
将不匹配任何内容。您需要将其更改为/RegItems/RegItem
或//RegItem
(后者在任何深度都可以找到RegItem
)。因此,例如,要获取Name
的{{1}}属性,您需要:
RegItem
答案 1 :(得分:1)
您遇到了一些问题:
/RegItem
。第一个/表示从文档的根部开始。根是RegItems
元素。您可以将其更改为/RegItems/RegItem
或//RegItem
(双斜杠表示可以在XML树中的任何位置找到该元素。->item(0)
,例如$xml->xpath("/RegItems/RegItem")->item(0)
getAttribute()
,例如$xml->xpath("/RegItems/RegItem")->item(0)->getAttribute('Name')