实际数据,更新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数据,现在我想在“描述”中搜索一些像“GOOD”这样的关键词然后如何用PHP搜索它?
<?php
foreach ($xml->property as $property)
{
//echo $property->details->description;
if ($property->details->description == 'good')
{
echo "SUCCESFuL";
}
echo "NON SUCCESFUL";
}
?>
答案 0 :(得分:0)
你可以使用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为您执行此操作并仅返回具有“好”的属性。在描述中。 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";
}
}