0

I have a page test.php in which I have a list of names:

name1: 992345
name2: 332345
name3: 558645
name4: 434544

In another page test1.php?id=name2 and the result should be:

332345

I've tried this PHP code:

<?php 
libxml_use_internal_errors(true); 
$doc = new DOMDocument(); 
$doc->loadHTMLFile("/test.php"); 
$xpath = new DOMXpath($doc); 
$elements = $xpath->query("//*@".$_GET["id"]."");
if (!is_null($elements)) {
foreach ($elements as $element) {
$nodes = $element->childNodes;
foreach ($nodes as $node) {
echo $node->nodeValue. "\n";
}
}
}
?>

I need to be able to change the name with GET PHP method in test1.pdp?id=name4

The result should be different now.

434544

is there another way, becose mine won't work?

4

2 回答 2

1

这是另一种方法。

<?php 
libxml_use_internal_errors(true); 

/* file function reads your text file into an array. */
$doc = file("test.php"); 

$id = $_GET["id"];

/* Show your array. You can remove this part after you 
 * are sure your text file is read correct.*/

echo "Seeking id: $id<br>";
echo "Elements:<pre>";
print_r($doc);
echo "</pre>";

/* this part is searching for the get variable. */

if (!is_null($doc)) {
    foreach ($doc as $line) {
        if(strpos($line,$id) !== false){
            $search = $id.": ";
            $replace = '';
            echo str_replace($search, $replace, $line);
        }
    }
} else {
    echo "No elements.";    
    }
?> 
于 2013-04-27T18:35:52.630 回答
0

有一种完全不同的方法可以做到这一点,将 PHP 与 JavaScript 结合使用(不确定这是否是您所追求的以及它是否可以与您的应用程序一起使用,但我将编写它)。您可以更改您test.php以读取 GET 参数(它也可以是 POST,您会看到),并据此仅输出所需的值,可能来自您在那里硬编码的关联数组。JavaScript 方法将有所不同,它将涉及进行单个 AJAX 调用,而不是使用 PHP 遍历 DOM。

因此,简而言之:AJAX 调用test.php,然后根据 GET 或 POST 参数输出所需的值。

jQuery AJAX在这里;本机 JS 教程在这里

如果这不适用于您的应用,请告诉我,我将删除我的答案。

于 2013-04-27T18:35:27.117 回答