我有一个PHP,我在一个查询XML文件的Q& A论坛中找到了:
$doc = new DOMDocument; // Create a new dom document
$doc->preserveWhiteSpace = false; // Set features
$doc->formatOutput = true; // Create indents on xml
$doc->Load('i.xml'); // Load the file
$xpath = new DOMXPath($doc);
$query = '//users/user/firstname[.= "'.$_POST["search"].'"]'; // The xpath (starts from root node)
$names = $xpath->query($query); // A list of matched elements
$Output="";
foreach ($names as $node) {
$Output.=$doc->saveXML($node->parentNode)."\n"; // We get the parent of "<firstname>" element (the entire "<user>" node and its children) (maybe get the parent node directly using xpath)
// and use the saveXML() to convert it to string
}
echo $Output."<br>\n\n"; // The result
echo "<hr><br><b>Below view the results as HTML content. (See also the page's HTML code):</b>\n<pre>".htmlspecialchars($Output)."</pre>";
该脚本将从firstname
的输入中搜索XML文档中所有POST
个节点的值,并返回节点firstname
的父节点,如果POST
输入值与任何节点值匹配。
此脚本运行良好,但它只返回包含firstname
节点的整个值的查询,如果我搜索节点文本的子字符串(例如{{1}的查询),则无效}将返回Potato
,但Potato
的查询不会给我Pot
的结果。
那么如何得到一个只包含节点文本的子串而不是整个值的结果呢?