我需要使用PHP获取值为“Bottle Number”的字段之后的值段的值(1250)。这是xml的片段......
<CustomerRecordExtraInfo>
<Field>1</Field>
<Value>1</Value>
<DateSaved>2013-11-15T12:21:35</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
<CustomerRecordExtraInfo>
<Field>Bottle Number</Field>
<Value>1250</Value>
<DateSaved>2013-12-11T15:22:34</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
<CustomerRecordExtraInfo>
<Field>City</Field>
<Value>Heath</Value>
<DateSaved>2013-12-11T15:22:34</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
答案 0 :(得分:0)
您可以使用 SimpleXML 解析它。
我与您分享了两种方法,首先是索引,第二次是迭代。
在解析XML之前,你应该将它包含在根元素(任何名称)中,我也添加了XML信息(版本)。
<?php
$input = <<<XML
<?xml version='1.0' standalone='yes'?>
<root>
<CustomerRecordExtraInfo>
<Field>1</Field>
<Value>1</Value>
<DateSaved>2013-11-15T12:21:35</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
<CustomerRecordExtraInfo>
<Field>Bottle Number</Field>
<Value>1250</Value>
<DateSaved>2013-12-11T15:22:34</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
<CustomerRecordExtraInfo>
<Field>City</Field>
<Value>Heath</Value>
<DateSaved>2013-12-11T15:22:34</DateSaved>
<SourceType />
<SourceID />
</CustomerRecordExtraInfo>
</root>
XML;
$xml = new SimpleXMLElement($input);
// Approach 1 - index
echo $xml->CustomerRecordExtraInfo[1]->Value;
// Approach 2 - iterative
foreach($xml->CustomerRecordExtraInfo as $customer) {
if($customer->Field == "Bottle Number") {
echo $customer->Value;
break;
}
}
?>
答案 1 :(得分:0)
使用xpath
,XML的'查询语言':
// $xml holds the simplexml object
$result = $xml->xpath("//CustomerRecordExtraInfo[Field = 'Bottle Number']");
echo $result[0]->Value;