我需要使用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>
您可以使用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;
}
}
?>
使用xpath
,一种用于XML:的"查询语言"
// $xml holds the simplexml object
$result = $xml->xpath("//CustomerRecordExtraInfo[Field = 'Bottle Number']");
echo $result[0]->Value;
看到它工作:http://codepad.viper-7.com/pp7IBJ
$dom = new DOMDocument();
$dom->loadXml($xml);
$xpath = new DOMXpath($dom);
var_dump(
$xpath->evaluate('string(//CustomerRecordExtraInfo[Field = "Bottle Number"]/Value)')
);
获取文档中任意位置的所有CustomerRecordExtraInfo元素:
//CustomerRecordExtraInfo
只有当有一个子元素"字段"和文本内容"瓶号"
//CustomerRecordExtraInfo[Field = "Bottle Number"]
获取子元素"值"找到的节点
//CustomerRecordExtraInfo[Field = "Bottle Number"]/Value
并将其转换为字符串(数字也是可能的)
string(//CustomerRecordExtraInfo[Field = "Bottle Number"]/Value)