我需要在所有节点上的 XML 文件中创建字符串搜索。
---目录.xml---
<?xml version="1.0" encoding="ISO-8859-1"?>
<Catalog>
<Category>
<Name>Biscuit</Name>
<Location>
<Id>Butter</Id>
<Description>The butter biscuit cost $10 per pack</Description>
</Location>
<Location>
<Id>Chocolate</Id>
<Description>The chocolate biscuit cost $20 per pack</Description>
</Location>
</Category>
<Category>
<Name>Cake</Name>
<Location>
<Id>Cup</Id>
<Description>This is a cup cake</Description>
</Location>
<Location>
<Id>Slice</Id>
<Description>This is a slice cake</Description>
</Location>
</Category>
</Catalog>
---search.php---
<?php
$catalog = simplexml_load_file("catalog.xml");
$category = $catalog->Category;
$location = $category->Location;
foreach($location->Description as $desc)
{
$string = string($desc);
$find = 'chocolate';
$result = strpos($string, $find)
if ($result !== false)
{
echo $result;
}
else
{
echo "No Result";
}
}
?>
我收到的错误是:
Parse error: syntax error, unexpected T_IF on line 14
由于节点和节点都有“巧克力”,我需要显示两个节点结果。
----新修订守则 / 2012 年 11 月 20 日---
<?php
$catalog = simplexml_load_file("catalog.xml");
$find = "chocolate";
$lcFind = strtolower($find);
$ll = implode('', range('a', 'z'));
$ul = strtoupper($ll);
$xpath_result = $catalog->xpath("//*[contains(translate(text(), '$ul','$ll'),'$lcFind')]");
if ($xpath_result) {
foreach ($xpath_result as $res) {
$category = $catalog->Category;
$name = $category->Name;
$loc = $category->Location;
$id = $loc->Id;
echo "Category: ", $name, "<br />";
echo "ID: ", $id, "<br />";
echo "Description :", $res, "<br />";
}
}
else {
echo "No matching descriptions found for word '<i>$find</i>'<br />";
}
?>
结果(错误):
类别:饼干 ID:黄油 //这应该是“巧克力” 描述:巧克力 //这应该是“巧克力”的描述 类别:饼干 ID:黄油 描述:巧克力饼干每包 20 美元