Jump to content

Crap! I've been asked to change my PHP ! Its been working for years!


JTapp

Recommended Posts

From what I gather from your posts, this contains your missing puzzle pieces:

 

function http_json_post($url, $data) {
  $ch = curl_init($url);
  curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_CUSTOMREQUEST  => 'POST',
    CURLOPT_POSTFIELDS     => $data_string = json_encode($data), // your data in JSON: {"name":"JTapp","age":"50"}
    CURLOPT_HTTPHEADER     => array(
      'Content-Type: application/json', // tell the server we are sending it JSON
      'Content-Length: ' . strlen($data_string)) // tell it how long it is
    )
  ));
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}

$webservice_url = 'http://webservice.local/data.json'; // actual API URL
$result = http_json_post($webservice_url, array('name' => 'JTapp', 'age' => 50));
If this does not work, then state the returned error. Edited by ignace
Link to comment
Share on other sites

There are several methods for requesting something from another site, from fopen to file_get_contents to curl to sockets to using ftp. But there's nothing we can really do to help your specific issues with them, unless we know specific details about the problem. What does the remote server expect in the request? What does it give as a response? etc..

 

No, you don't have to post code, and we do in fact warn against posting code that you do not want to have publicly available. We provide free help when we are able, and the exchange for that is that it's public. That's how most "free" sites work. If you want private help, you will have to pay for it (e.g. hire a freelancer).

 

So you can't post the code because it's private. But you can't get help without posting code. You are right; it is sort of a catch-22. But how on earth do you expect us to help when you don't? Are you really getting upset at us because we aren't psychic?

Link to comment
Share on other sites

ignace - I found an extra closed parenthesis and got rid of it, then the last line caused a hang up and ultimately it produced an internal server error

upon removing it I got zero errors, but I also got zero data

 

I tried changing $result to the $echo line as shown below - which is the code I'm using - but now all I'm getting is the single word "Array"

 

Thank you

<?php

$url = 'myapiurl';
$data = array('a_field_title' => 'desired_result', 'a_field_title2' => 'desired_result2');

function http_json_post($url, $data) {
  $curl = curl_init($url);
  curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_CUSTOMREQUEST  => 'POST',
    CURLOPT_POSTFIELDS     => $data_string = json_encode($data), // your data in JSON
    CURLOPT_HTTPHEADER     => array(
      'Content-Type: application/json', // tell the server we are sending it JSON
      'Content-Length: ' . strlen($data_string)) // tell it how long it is
    )
  );
  $output = curl_exec($curl);
  curl_close($curl);
  return $output;
}

$webservice_url = 'actualAPI_URL'; // actual API URL
echo $data;

?>

Link to comment
Share on other sites

The API developer -

 

"The API will pass back XML formatted or JSON formatted and it is in compliance with Web API 2.

GET api?/productname?requiredfieldID={desiredfieldID}

 

The requiredfieldID has to be defined in the request URI"

 

This is where I'm getting hung up on the json_decode and how the array is configured.

Link to comment
Share on other sites

Look at ignaces code again. You have not called http_json_post(). You should be passing $url as the first argument and then $data as the second argument.

 

$result should then contain the json returned from your api. To convert the json into an array use json_decode

 

Based on this feedback I sat through a json course on lynda.com looking for anything that spoke to http_json_post()

Now I understand that is not a standard item.

I've also read ALOT about json_decode and have explored the world of $params 

Figuring I needed to utilize the API documentation, I tried to insert

$params = array('field name' => 'desired result');

 

 

I believe I've gone full circle.

Don't be hatin' though

 

Three days of non-stop attempted self-education has demonstrate that I'm trying, right?

Link to comment
Share on other sites

Ok.. in the off chance the recommendation was a typo, I changed http_json_post to

http_post_data

 

That didn't do anything.

I can't seem to find consistency on the internet regarding how to write what is in the API Documentation:

 

GET api/NAMEOFAPI?PrimaryNameID={DesiredPrimaryNameID}

 

The error message that I'm getting is Internal Server Error

I'm sure it has to do with how I'm posting the parameters.

Its also clear that I don't understand the difference between $url and $webservice_url.

All help is appreciated..

<?php

$url='http://xx.xxx.org/xxx/xxx/xxxWebApi.mode'; //Am I supposed to put a concatenated ? after .mode ?
$data = array(NameOfField => 'IDnumber');
	
function http_json_post($url, $data) {
  $ch = curl_init($url);
  curl_setopt_array($ch, array(
    CURLOPT_RETURNTRANSFER => 1,
    CURLOPT_CUSTOMREQUEST  => 'POST',
    CURLOPT_POSTFIELDS     => $data_string = json_encode($data), 
    CURLOPT_HTTPHEADER     => array(
      'Content-Type: application/json', // tell the server we are sending it JSON
      'Content-Length: ' . strlen($data_string)) // tell it how long it is
    )
  );
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}

$webservice_url = 'http://xx.xxx.org/xxx/xxx/xxxWebApi.mode/api/NAMEofAPI?NameOfField=Value'; // actual API URL
$result = http_json_post($webservice_url, array('NameofField' => 'value'));

?>
Link to comment
Share on other sites

Don't be hatin' though

 

Three days of non-stop attempted self-education has demonstrate that I'm trying, right?

It's not that we are being haters, or that we don't think you are trying. We simply cannot provide any sort of help with the information you are willing to provide. It's like if you ride your bicycle up to the auto-mechanics to tell them your car is broken and ask for help fixing it, but when they ask what's the issue is or if they can see your car you say "Sorry, that's private".

 

Ok.. in the off chance the recommendation was a typo, I changed http_json_post to

http_post_data

The code given to use was a custom function. That is why there is no mention of it in the tutorials/classes you may have watched. Changing the name will not do anything to affect the outcome either.

 

I can't seem to find consistency on the internet regarding how to write what is in the API Documentation:

 

GET api/NAMEOFAPI?PrimaryNameID={DesiredPrimaryNameID}

 

 

There really isn't any consistency for how an API accepts or returns data. That is why we cannot help you because in order to we'd need to be able to see the API (or documentation at least) to determine how it works. Every API is different with regard to how you pass data to it or get data from it. JSON or XML are common mediums for transferring data but that tells you nothing about the actual data you need to send/get (ie, parameter names, order of fields, etc).

 

Based on what you have stated the API seems to expect a GET request with various parameters in the query string of the URL. What this means is you can use a simple file_get_contents to query the API and see the results without having to mess around with trying to send POST data which is what the help you have thus far received has been oriented toward.

 

Being a simple GET request means you can test the API your browser also by simply entering the URL into your address bar and checking the data returned. Once you get data you expect you can start on your PHP code to issue the request and work with the result.

 

So, here is the basic steps of how you start trying do what you need:

  • Start with your browser
    • Input the Web API URL in your address bar
    • Add the parameters you think it needs in the query string and load the page
    • If you get an error, repeat step b. If you get expected results, move on
  • Code your PHP
    • Take the URL from your address bar and put it into your PHP code as a variable; $url="copy/paste url here"
    • For a simple GET request, all you need to do is use file_get_contents to load response. Use the URL as the first parameter, assign the result to a variable
    • var_dump the variable returned by file_get_contents and ensure it contains similar content to what shows in the browser when you make the api request.
    • When var_dump shows the expected results, move on
  • Process the results
    • Determine what kind of result you are getting. Is it XML? JSON? Something else. JSON is common because it is easy, but XML is still used.
    • If you are getting a JSON result you would use json_decode to convert the data into a PHP object or array for processing.
    • If you are getting a XML result then you'll need to use either SimpleXML or DOMDocument to access the information.
In order for us to provide any more specific help than that you need to be able to provide us with more specific information such as API documentation. You can always try and edit out whatever confidential/proprietary information you need to but you still need to convey the usage of the API.
Link to comment
Share on other sites

The following code worked.

After researching and discovering there are curl issues with the php.ini file - and choosing not to edit the .ini,

I found this absolute alternative

It ain't pretty but I didn't expect it to be.

<?php
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.apiwebsite.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);
$result = preg_replace("#(<\s*a\s+[^>]*href\s*=\s*[\"'])(?!http)([^\"'>]+)([\"'>]+)#",'$1http://www.apiwebsite.com/$2$3', $result);
echo $result
?>

Edited by JTapp
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.