实际数据,更新3.实际数据,实际数据
<?xml version="1.0" encoding="UTF-8"?>
<properties>
<property>
<location>
<street-address>xyz</street-address>
<city-name>zyx</city-name>
</location>
<details>
<price>111111</price>
<description>xyz</description>
</details></property>
<property>
<location>
<street-address>xyz</street-address>
<city-name>zyx</city- name>
</location>
<details>
<price>111111</price>
<description>xyz</description>
</details></property>我有这个xml数据,现在我想在"description“中搜索一些关键字,比如"GOOD”,然后如何使用PHP搜索它呢?
<?php
foreach ($xml->property as $property)
{
//echo $property->details->description;
if ($property->details->description == 'good')
{
echo "SUCCESFuL";
}
echo "NON SUCCESFUL";
}
?>发布于 2018-04-03 15:11:29
您可以使用XPath,尽管我假设有一个属性列表(我刚刚向源XML添加了另一个级别)。
$data = <<< XML
<List>
<property><location>USA</location>
<detail>
<state>NY</state>
<city>new york</city>
<description> NY is good city </description>
</detail>
</property>
</List>
XML;
$xml = simplexml_load_string($data);
$goodProperty = $xml->xpath("//property[detail/description[contains(translate(.,'ABCDEFGHIJKLMNOPQRSTUVWXYZ','abcdefghihklmnopqrstuvwxyz'),'good')]]");
foreach ( $goodProperty as $property ) {
echo $property->location."-".$property->detail->description.PHP_EOL;
}这样就省去了每个条目的循环,就像XPath为您所做的那样,并且只返回描述中有'good‘的属性。XPath的尴尬之处在于确保它不区分大小写,这正是translate所做的。
这个输出(对于样本)..。
USA- NY is good city 更新:
或者简单的检查是否存在..。
$xml = simplexml_load_string($data);
foreach ( $xml->property as $property ) {
if ( stripos($property->detail->description, "good") !== false ){
echo "Success";
}
else {
echo "Non Success";
}
}stripos进行不区分大小写的搜索,如果没有找到,则返回false。
更新2a:
$filename ="data.xml";
$xml = simplexml_load_file($filename);
if ( stripos($xml->detail->description, "good") !== false ){
echo "Success";
}
else {
echo "Non Success";
}data.xml中含有..。
<?xml version="1.0" encoding="utf-8"?>
<property>
<location>
<street-address>xyz</street-address>
<city-name>zyx</city-name>
</location>
<detail>
<price>699900</price>
<description>xyz good</description>
</detail>
</property>更新3.1..。
$xml = simplexml_load_file($filename);
foreach ( $xml->property as $property ) {
if ( stripos($property->details->description, "good") !== false ){
echo "Success";
}
else {
echo "Non Success";
}
}https://stackoverflow.com/questions/49633044
复制相似问题