• 0

PHP Curl and multiple URLs?


Question

I'm trying to use curl to get a value but need some help. What I want is to check a url and if the value is null, try another url and return the value. This is all while using xml.

my code:

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($contentlength));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);

if ($xml->jid=="") {
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $newUrl);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($contentlength));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
}
if ($xml->id!="") {
echo('jid:' . $xml->id . "<br/>");
} else {
echo "id not found";
}

EDIT: This works for now, but was hoping for less redundancy.

Edited by DPyro
Link to comment
Share on other sites

2 answers to this question

Recommended Posts

  • 0

You'll have to do another cURL call.

You could put it in a loop or something through:

foreach (array("URL1","URL2","URL3") as $url) {
  //Your code
  if (!empty($xml->id)) {
    break;
  }
}

Link to comment
Share on other sites

  • 0

Thanks, that's much better:

foreach (array($url1,$url2,$url3) as $url) {

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_HTTPHEADER, array($contentlength));
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $inputdata);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
$data = curl_exec($ch);
curl_close($ch);
$xml = simplexml_load_string($data, 'SimpleXMLElement', LIBXML_NOCDATA);
if (!empty($xml->id)) {
    break;
  }
}

if (!empty($xml->id)) 
echo('id:' . $xml->id . "<br/>");
} else {
echo "id not found";
}

That's actually simpler than I imagine :)

Link to comment
Share on other sites

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.