简体   繁体   中英

Trying to send a http get request from a php file to a server and receive a http response

I'm trying to send a http get request in a php file to a server and receive the response.

function broadcastRequest($catCommand,$command,$prop){
    $ch = curl_init();
    curl_setopt ($ch, CURLOPT_URL,'http://'.$prop["ipServer"].':'.$prop["portVLM"].$prop["startURL"].$catCommand."%20".$prop["broadcastName"].'%20'.$command);
    curl_setopt ($ch, CURLOPT_HEADER, 0);
    $res = curl_exec ($ch);
    $res = simplexml_load_file($res);   
    curl_close ($ch);
}
  • If I echo the first $res I can read the number 1
  • the second $res won't load because simplexml_load_file() isn't syntax-highlighted in my Notepad++

Can someone explain to me what I'm doing wrong, or advise another way of working?

First of all, Notepad++'s syntax highlighting has absolutely nothing to do with whether it's valid. It just reads names, and you'll notice that simplexml_load_file is never highlighted.

Now onto the problem. $res is just a boolean value returned by curl_exec , because you haven't set the CURLOPT_RETURNTRANSFER option, as specified in the docs. However, a simpler way is just loading it directly:

function broadcastRequest($catCommand,$command,$prop) {
    $res = simplexml_load_file('http://' . $prop["ipServer"] . ':' . $prop["portVLM"] . $prop["startURL"] . $catCommand . '%20' . $prop["broadcastName"] . '%20' . $command);
}

If you'd like to use cURL, however, just set the additional option:

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

Looks like you need to set the CURLOPT_RETURNTRANSFER option. However, it's probably easier to just do this:

$res = file_get_contents($uri);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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