I'm trying to get some data from a specific API. If I do a test run on the API page, they give me this url back as a response, so I can get the api data from there:
( only categorie snippet )
&categories=1%2C2%2C3%2C4%2C5%2C6%2C7%2C8%2C9%2C10%2C11%2C12"
Basically that means: 1,2,3,4,5,6,7,8,9,10,11,12
I have a categorie array, with also 12 elements.
The array looks like this:
dd($this->categories) outputs:
array:12 [▼
0 => "1"
1 => "2"
2 => "3"
3 => "4"
4 => "5"
5 => "6"
6 => "7"
7 => "8"
8 => "9"
9 => "10"
10 => "11"
11 => "12"
]
to make an api request from my system, the url I call must have the same standard as from the api test. However, thats how my URL looks like ( only categorie snippet )
&categories=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%2C%225%22%2C%226%22%2C%227%22%2C%228%22%2C%229%22%2C%2210%22%2C%2211%22%2C%2212%22%5D
code snippet:
$categories = "&categories=" . rawurlencode(json_encode($this->categories));
As you can see, the url snippet of the api test is much shorter than mine. I think thats because of the encoding?
I tried to solve it with convert the array to json first and used the rawurlencode method on it. But this haven't solved the problem for me. I need to "convert" the url in the same way, the api does it.
Does anyone have an idea how I can solve this problem?
What I found:
I have found this snippet that nearly solved my problem
$categories = "&categories=" . http_build_query($this->categories, null, "%2C", PHP_QUERY_RFC1738);
The result looks like this:
&categories=0=1%2C1=2%2C2=3%2C3=4%2C4=5%2C5=6%2C6=7%2C7=8%2C8=9%2C9=10%2C10=11%2C11=12
But I really don't know where ne 0 at the beginning comes from and why there is always a "=" character after every array element
If you inspect your variables you'll see that URL encoding has nothing to do with the issue:
var_dump(rawurldecode('categories=%5B%221%22%2C%222%22%2C%223%22%2C%224%22%2C%225%22%2C%226%22%2C%227%22%2C%228%22%2C%229%22%2C%2210%22%2C%2211%22%2C%2212%22%5D'));
string(63) "categories=["1","2","3","4","5","6","7","8","9","10","11","12"]"
Please compare:
$categories = array('1', '2', '3');
var_dump(json_encode($categories));
var_dump(implode(',', $categories));
string(13) "["1","2","3"]"
string(5) "1,2,3"
http_build_query()
is overkill here. You don't really have any complex structure, just a single string variable.