简体   繁体   English

连接PHP中的xPath查询

[英]Concatenating an xPath query in PHP

I'm using xPath to query a HTML document. 我正在使用xPath查询HTML文档。 I'm setting a string as the contents of the xPath query. 我正在将字符串设置为xPath查询的内容。 So in this case '$category_titles' is set to the the text that the query returns. 因此,在这种情况下,'$ category_titles'被设置为查询返回的文本。

$category_titles = $xpath->query('//*[@id="test"]/div/div/h1');

Is there a way to pass in the values of two xpath queries in to my string though? 有没有办法将两个xpath查询的值传递给我的字符串? So effectively, I need to set $category_titles to the result of two separate xPath values. 如此有效,我需要将$ category_titles设置为两个单独的xPath值的结果。

You should use operator | 您应该使用运算符| to merge more than one different paths into one. 将多条不同的路径合并为一条。 this is valid: 这是有效的:

$titles = $xpath->query('//*[@id="test"]/div/div/h1 | //*[@id="test1"]/div/div/h1');

I don't know if I understood what you want exactly, but if you are trying to have two xpath results in the same variable, the only way is using a array . 我不知道我是否确切地了解您想要什么,但是如果您尝试在同一个变量中包含两个xpath结果,则唯一的方法是使用array

$category_title = array();
$category_titles[0] = $xpath->query('//*[@id="test"]/div/div/h1');
$category_titles[1] = $xpath->query('//*[@id="test1"]/div/div/h1');//I changed the ID, but you can change your entire query

Then, if you want to concatenate it, just a $concat = "$category_titles[0]" . "$category_titles[1]" 然后,如果要串联它,只需$concat = "$category_titles[0]" . "$category_titles[1]" $concat = "$category_titles[0]" . "$category_titles[1]" is enough. $concat = "$category_titles[0]" . "$category_titles[1]"就足够了。

However, if you are trying create a second query using the result of first one and then concatenate, you can do: 但是,如果尝试使用第一个查询的结果创建第二个查询然后进行串联,则可以执行以下操作:

$category_titles = $xpath->query('//*[@id="test"]/div/div/h1');
$category_titles = "$category_titles" . $xpath->query("//*[@id=\"$category_titles\"]/div/div/h1");// Note the escaped slashes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM