Searching XML items PHP XPath

丶灬走出姿态 提交于 2019-12-01 11:03:51
hakre

So you want to know, how to select all children of <items><item> elements that contain the text search for with xpath (I leave case sensitivity out, you find that on the linked answers). First of all, all item elements:

//items/item

You already have that. To only return those that contain some text, add the predicate:

//items/item[contains(., 'XYZ')]

If you only want to search within the <title> child element:

//items/item[contains(title, 'XYZ')]

This is basically what you have already, however you make your live needlessly hard: You don't need to do that twice, you can just iterate over the matches directly:

$nodes = $xml->xpath("//items/item[contains(title, 'XYZ')]");
foreach ($nodes as $node)
{
    foreach ($node as $name => $prop) {
        printf("%s: %s\n", $name, $prop);
    }
    echo "\n";
}

Output:

id: 3
title: Title XYZ
author: Author Name
description: Description text 

To learn about how to escape input to xpath (which is read-only, so this is not as dangerous as a SQL injection), consider the following example:

$query = 'XYZ';
$expression = sprintf("//item[contains(title,'%s')]", $query);
$nodes = $xml->xpath($expression);

It will create the following expression:

//item[contains(title,'XYZ')]

But what happens if there is some single quote in there? It will terminate the string and therefore create an error:

$query = 'd\'oh';

Will give:

Warning: SimpleXMLElement::xpath(): Invalid expression in ...

You can prevent this by doing something as outline here, specifically assigning the value to the document and comparing against it then:

$query = 'd\'oh';
$xml['query'] = $query;
$nodes = $xml->xpath("//item[contains(title, /*/@query)]");

Old: You ask multiple questions at once:

  1. How to search with xpath case-insensitive
  2. How to find out about relevancy (so to sort it by relevance)

Relevance is undefined. What could be relevant for one could be irrelevant for others, so it's hard to answer that part of your question without a specific definition on how relevancy could be metriced.

For case-insensitivity search, duplicate questions have been already linked, so you should be able to do that. Best first dulicate in my eyes:

But here as well it remains undefined what case, lower and upper, is. You have not specified a thing, so your question can not be really answered.

Also you don't really validate your input:

$query = $_GET['query'];
$nodes = $xml->xpath("//item[contains(title,'$query')]");

It's possible to inject xpath here with the GET parameter. Take care, otherwise you won't do any search at all.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!