问题
I am using Solr and have the following query which works fine from my browser:
http://www.someipaddress.com:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+%26+Lomb"
In part of the return xml I see:
<str>manufacturer:"Bausch & Lomb"</str>
However when I try and get the above url using simplexml_load_file like this:
$xml = simplexml_load_file("http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:\"Bausch+%26+Lomb\"");
I get no results because Solr is being passed the manufacturer string that looks like this (from print_r):
[str] => Array ( [0] => shopid:40 [1] => manufacturer:"Bausch+%26+Lomb" )
So when I am doing the query through the browser I pass in %26 but it deals with it correctly in the query. But when I use simplexml_load_file it remains as %26 and so the query fails.
回答1:
Try:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"'))
See note on file
parameter: http://php.net/manual/en/function.simplexml-load-file.php
回答2:
Didn't work:
$url = 'http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18';
$url .= '&fq=manufacturer:"Bausch' .urlencode('&'). 'Lomb"';
simplexml_load_file(rawurlencode($url));
Manufacturer part of query came out as: "Bausch&Lomb"
;
Didn't work:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch ' .urlencode('&'). ' Lomb"'))
Adding spaces next to the words Bausch and Lomb produced simplexml_load file error.
Worked:
simplexml_load_file(rawurlencode('http://127.0.0.1:8983/solr/select?q=*&fq=shopid:40&start=0&rows=18&fq=manufacturer:"Bausch+' .urlencode('&'). '+Lomb"'))
Swapping spaces for + works!
This is how I ended up doing it dynamically.
$manufacturer = urlencode("Bausch & Lomb");
$manufacturer_insert = "&fq=manufacturer:\"$manufacturer\"";
$xml = simplexml_load_file(rawurlencode("http://127.0.0.1:8983/solr/select?q=$shopid_insert$start_insert$rows_insert$sort_insert$manufacturer_insert"));
That works for manufacturers with an ampersand in their name.
It is important to note that if you were passing values with spaces they will now need to be urlencoded before being added. For example:
Before I could just use this for my sort insert:
$sort_insert = "&sort=price desc";
Now I need to urlencode just "price desc". When I tried to urlencode the whole sort_insert string the simplexml query would fail.
After (works):
$sort = urlencode("price desc");
$sort_insert = "&sort=$sort";
Thanks again... Back to the project!
来源:https://stackoverflow.com/questions/7806458/simplexml-load-file-with-ampersand-in-url-with-solr