How to use an API in my program?

Hi,
I want to use a link which has been written by API in my program, I do not know how to use it?
When I open link, It returns correct results, However in my code it returns the following error:
Warning: Invalid argument supplied for foreach()


if (isset($_POST['material-code']) && $_POST['material-code']!="") { 
$material_code = $_POST['material-code']; 
$url = "http://localhost:1367/rest-api - Copy/api-alis.php?material_code=".$material_code;

$client = curl_init($url); 
curl_setopt($client,CURLOPT_RETURNTRANSFER,true); 
$response = curl_exec($client); 

$result = json_decode($response);


 foreach ($result as $results) {
      
         print "{$results->material_code} {$results->importation_quantity} \n";
      }
} 

How to solve it?
Thanks in advance

That error means $results isn’t what you expected it to be, probably because $response isn’t what you expect it to be. Try printing out $response before attempting to decode it, see what it says.

1 Like

Mohamad, is your $material_code an integer or a string? My guess is a string. If so, you need to handle it differently than you are now. Something like this should work:

Note: The last part is double-quote single-quote double-quote. This places single quotes around the data which I am guessing is a string and not an integer number.

If your material code is actually an integer number, then most likely you have a problem with your curl routine. Curl has many more commands to add that you are missing. Also, you are using JSON to decode the output. It may not be in JSON format. If you go to the page with the URL and it displays the data, you can then RIGHT-CLICK on the page and select VIEW-SOURCE depending on the browser used and actually look at the data the page is returning. With that display, you can figure out how you must decode it. My guess is that if the input is an integer value and is displayed on a webpage, then it is most likely not in JSON format, but, in HTML format instead. One more note, you can try this in your test page code above:

This will display what is really inside the results variable. It should show you exactly what you are being returned from the CURL code.
Hope this helps you debug it…

Because your url contains spaces (I edited your post to change the <code></code> to bbcode [code][/code] tags), you must urlencode() it when using it in a program statement or more simply don’t use spaces in urls. When you enter it in a browser’s address bar, the browser automatically urlencodes it for you. If you look the address bar in the browser, it ended up being - http://localhost:1367/rest-api%20-%20Copy/api-alis.php?material_code=123

If you do what @skawid suggested, of echoing $response, you should see a message about a Bad Request … http 400 error.

1 Like

Thanks for your considerations,
When I enter URL in my browser, the browser shows something like this:

{“material_code”:“1”,“importation_quantity”:“125”}{“material_code”:“1”,“importation_quantity”:“150”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:“250”}{“material_code”:“1”,“importation_quantity”:“500”}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:""}{“material_code”:“1”,“importation_quantity”:“2000”}{“material_code”:“1”,“importation_quantity”:""}

And when I var_dump ($response) instead of $result , the browser shows something like this:

<small>D:\wamp64\www\rest-api - Copy\fetch.php:12:</small>
<small>string</small>
 '<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
 <html>
<head>
 <title>301 Moved Permanently</title>
 </head>
<body>
 <h1>Moved Permanently</h1>
 <p>The document has moved <a href="http://localhost:1367/rest-api/">here</a>./p>
 <hr>
 <address>Apache/2.4.23 (Win64) PHP/5.6.25 Server at localhost Port 1367</address>
 </body>
</html> '
 *(length=326)*

By the way, material_code is a number(integer)

Try this CURL code instead:

$client = curl_init();
curl_setopt($client, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL,$url);
$result=curl_exec($client);
curl_close($client);
var_dump(json_decode($result, true));

And let us know if you get results or not.

1 Like

Ok. That looks like your browser is following a redirect to get to the correct URL. A CURL request won’t do that. In the $response you’ve dumped, there’s a link to the new location of the URL. Replace the URL you’re using with that one and you should be away.

1 Like

See the FOLLOWLOCATION and MAXREDIRS options - https://thisinterestsme.com/php-curl-redirects/

1 Like

Skawid, yes, you can follow it. It’s a CURL option. But, I think it is something else.
He needs to see what is actually being pulled first and then we can sort it out.

1 Like

Thanks for your time and considerations,
Dear Ernie, I tested your code, the browser shows this error/message:

“wamp64\www\rest-api - Copy\fetch.php:14:null”

Skawid, Can you please describe in more details?

phdr, your link is not opened for me
Thanks again

did you try to make the request in CURL on your system?

301 Moved Permanently is a HTTP response code - that’s a standard number and description of the status of a HTTP response. There are a lot of them, but this one means that the URL you’re trying to access no longer exists.

A 301 response is usually sent along with a new URL where you can find what you’re looking for. That’s the link in <p>The document has moved <a href="http://localhost:1367/rest-api/" rel="nofollow noopener">here</a>.</p>. A browser knows to follow this link automatically, but CURL doesn’t. That’s why you’re seeing two different responses.

You can probably set a flag to allow CURL to follow the new link automatically, but it would be more straightforward to just replace the URL in your code, so from:

$url = "http://localhost:1367/rest-api - Copy/api-alis.php?material_code=".$material_code;

to:

$url = "http://localhost:1367/rest-api/api-alis.php?material_code=".$material_code;

1 Like

It might be because you are attempting to get a locally hosted web address. It is adding in the http:// and that might be failing for you. I think you might want to either change to “file_get_contents” functions instead of CURL, or use your local IP instead. ( 127.0.0.0 )

On my WAMP system, webpages are located at D:\wamp\www\foldername…
Webpages are accessed in the browser using a URL of localhost/foldername/filename.php
Perhaps you just need to change the URL to the correct name.

Try:
$url = “localhost/rest-api - Copy/api-alis.php?material_code=’”.$material_code."’";

1 Like

Sorry, for the delay, Yes, I use it in my system

Thanks for your kind reply, It does not work, yet.

Dear Ernie, I tried with your ways, but unfortunately, the browser returns this error:
wamp64\www\rest-api - Copy\fetch.php:13:null

As I said before, when I use the following URL in my browser, the browser returns the correct result, but I do not know why curl cannot?!
http://localhost:1367/rest-api%20-%20Copy/api-alis.php?material_code=2

When I use the above URL browser returns this:
{“material_code”:“2”,“importation_quantity”:“200”}{“material_code”:“2”,“importation_quantity”:“3000”}{“material_code”:“2”,“importation_quantity”:“2500”}{“material_code”:“2”,“importation_quantity”:""}{“material_code”:“2”,“importation_quantity”:""}{“material_code”:“2”,“importation_quantity”:""}{“material_code”:“2”,“importation_quantity”:""}{“material_code”:“2”,“importation_quantity”:""}{“material_code”:“2”,“importation_quantity”:“5000”}{“material_code”:“2”,“importation_quantity”:""}

How to solve it? I can also share the API file, if it is necessary.
Thanks in advance

When you use the above in your browser, does the url change to anything else, such as the localhost/rest-api/ that’s burried in the moved permanently … output you got? (which I just added bbcode [code][/code] tags around so that it is readable.)

I’m thinking that the api code contains a (needless) redirect, that isn’t being executed when there is json output, due to content being output before a header(). The browser is causing the code to produce the json output, but something about the curl call isn’t.

At this point, we don’t have enough information about what is going on, so, yes post the code for the api.

1 Like

Mohamad, I am assuming since the api page is local that your cURL code is not set up correctly in your WAMP system. Or, for some reason the code I gave you is not working correctly due to other issues. But, I am thinking that your results is not really Json. Try just displaying the data to see what it actually gets from the results… Without decoding it from Json first. See if you actually get the page’s data.

$url = “localhost/rest-api - Copy/api-alis.php?material_code=123”;  // If 123 is a valid code!!!
$client = curl_init();
curl_setopt($client, CURLOPT_RETURNTRANSFER, true);
curl_setopt($client, CURLOPT_URL,$url);
$result=curl_exec($client);
curl_close($client);
var_dump($result);

OR, perhaps you should just use file-get-contents instead?

$result = file_get_contents($url);
$var_dump($result);

Less code but does not allow any special cURL code if needed…

But, lastly, your code is NOT standard JSON code. Here is an example of setting up a JSON array:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

As you see, numeric values do NOT have quotes around them. Your data would be treated as strings using your example from the browser:

{“material_code”:“1”,“importation_quantity”:“125”}{“material_code”:“1”,“importation_quantity”:“150”}

If you want to use them as strings, then, this is okay.

1 Like

I’m deeply grateful for your time and consideration,
I tested your ways, When I use the first solution that you have presented, the browser returns something like that:

301 Moved permanently. Also, when I use your second solution(file_get_contents($url)), the browser returns index.htm.

So, why when I enter the URL in browser, it returns valid data, but in fecth.php, it is not possible?
I will share the api.php for you. probably, it is rooted in that.
very best regards

Well, as Phdr mentioned, your page seems to be redirecting to another page.
When you type in the URL manually, does it stay on that page? Or does the URL change after you go to the page? Perhaps you can just look at the code in the rest-api - Copy/api-alis.php page and see what it does.
If you get a #301, it is not sending to the correct page. Either you entered it incorrectly, or you are being sent to another page. You would need to look at the code in the URL you are calling and figure out what is going on with it.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service