2
我試圖製作一個PHP文件,可以在XML文檔中搜索特定的魚。這是我寫的:PHP XPath查詢XML?
$FISH_NAME = $_POST["fish_name"];
$LOCATION = $_POST["location"];
$STATUS = $_POST["status"];
$EDIBLE = $_POST["edible"];
$SCS_NAME = $_POST["scs_name"];
$COLOR = $_POST["color"];
$FEATURE = $_POST["feature"];
$varsPassed = array(
$FISH_NAME => "NAME",
$LOCATION => "@LOCATION",
$STATUS => "STATUS",
$EDIBLE => "EDIBLE",
$SCS_NAME => "SCS-NAME",
$COLOR => "COLORS/COLOR",
$FEATURE => "FEATURES/FEATURE"
);
$conditional = "";
function addToCond($varPassed, $tagName) {
if (!empty($varPassed)) {
if(!empty($conditional)) {
$conditional .= " and {$tagName} = '{$varPassed}'";
}
else {
$conditional = "{$tagName} = '{$varPassed}'";
}
}
}
foreach($varsPassed as $current_feature => $current_tag_name) {
addToCond($current_feature, $current_tag_Name);
echo "{$current_feature}: {$current_tag_name}\n";
}
$query = "/FISHDICT/FISH[@LOCATION = 'REEF']";
echo $query;
$dom = new DOMDocument();
$dom->load('server/fish.xml');
$xpath = new DOMXpath($dom);
$value = $xpath->evaluate($query);
foreach($value as $item) {
echo "found: {$item->nodeValue}\n\n";
}
但它不起作用。我得到這個迴盪在網頁上:
神仙:NAME:特點/特徵/ FISHDICT/FISH [@LOCATION ='暗礁]
有誰知道爲什麼它通過每個不循環帖子變量?
XML:
<FISH location="REEF">
<NAME>Angelfish</NAME>
<COLORS>
<COLOR> Blue </COLOR>
<COLOR> Green </COLOR>
</COLORS>
<FEATURES>
<FEATURE> Round head </FEATURE>
<FEATURE> Crown on head </FEATURE>
<FEATURE> Tall tail fin </FEATURE>
</FEATURES>
<TAGS>
<TAG> REEF-FISH </TAG>
<TAG> MULTICOLORED </TAG>
</TAGS>
<STATUS> ENDANGERED </STATUS>
<DESCRIPTION> This fish is found in reefs and is common throughout Bermuda...</DESCRIPTION>
<FISHINGLEGAL> FALSE </FISHINGLEGAL>
<DIET>
<DIETITEM> Algae </DIETITEM>
<DIETITEM> Sea Plants </DIETITEM>
</DIET>
<EDIBLE> FALSE </EDIBLE>
<SCS-NAME> Holacanthus ciliaris </SCS-NAME>
</FISH>
當我輸入靜態值時,您的腳本適用於我。你確定你的POST名稱是正確的嗎?也不確定你是否期待將來使用'$ conditional',但目前的代碼中不會有任何內容。 – chris85 2015-04-05 22:02:17