我有以下xml内容:
<?xml version="1.0" encoding="UTF-8"?>
<methodResponse>
<params>
<param>
<value>
<array>
<data>
<value>
<array>
<data>
<value>
<string>Car</string>
</value>
<value>
<string>1</string>
</value>
</data>
</array>
</value>
<value>
<array>
<data>
<value>
<string>Plane</string>
</value>
<value>
<string>2</string>
</value>
</data>
</array>
</value>
<value>
<array>
<data>
<value>
<string>Boat</string>
</value>
<value>
<string>3</string>
</value>
</data>
</array>
</value>
</data>
</array>
</value>
</param>
</params>
</methodResponse>
我想只知道数据3
来取回数字Boat
这是我所做的:
$xml = new SimpleXMLElement($response);
$arr_response = $xml->params->param->value->array->data->value->array->data;
foreach ($arr_response as $key => $value) {
if($key == "Boat"){
echo "Found !";
echo "$key -> $value";
}else{
echo "Not found";
}
}
输出:
Not found
答案 0 :(得分:2)
由于您正在处理xml,因此仅使用xpath更为简单:
$xml = simplexml_load_string($response);
$boat = $xml->xpath('//data//value[string="Boat"]/following-sibling::value/string');
echo $boat[0];
输出:
3
答案 1 :(得分:0)
您可以按以下方式使用DomDocument
$doc = new DOMDocument();
$doc->loadXML($data);
$xpath = new DOMXPath($doc);
foreach ($xpath->query("//data[./value[1]/string[contains(text(), 'Boat')]]") as $boat) {
echo $boat->getElementsByTagName("string")[1]->textContent;
}