Solved

PHP, cURL and XML

Posted on 2013-02-07
7
534 Views
Last Modified: 2013-02-11
Hello

I've made quite some progress in PHP, cURL and XML so have shortened down my code and steps taken, now that I thought I had the code to a really good place I'm encountering one problem with the code being printed to the screen without me wanting it to, and it's not being stored in the variable as I had hoped, hoping someone can help me here...

<?php
    /**
     * Define POST URL and also payload
     */
    define('XML_PAYLOAD', '<?xml version="1.0"?><member><name>name</name></member>');
    define('XML_POST_URL', 'http://ec2.eu-west-1.compute.amazonaws.com:8080/AppServlet?method=showUser&userPhoneNo=07575');
       
    /**
     * Initialize handle and set options
     */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));
   
    /**
     * Execute the request and also time the transaction
     */
    $start = array_sum(explode(' ', microtime()));
    $result = curl_exec($ch);
    $stop = array_sum(explode(' ', microtime()));
    $totalTime = $stop - $start;
   
    /**
     * Check for errors
     */
    if ( curl_errno($ch) ) {
        $result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
    } else {
        $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        switch($returnCode){
            case 404:
                $result = 'ERROR -> 404 Not Found';
                break;
            default:
                break;
        }
    }
   
    /**
     * Close the handle
     */
    curl_close($ch);
   
    /**
     * Output the results and time
     */
    echo 'Total time for request: ' . $totalTime . "\n";
    echo $result;  
   
    /**
     * Exit the script
     */
    exit(0);

echo $result;

$xml = simplexml_load_string($result);
// loop begins
foreach($xml->Queues->Queue as $Customer)
{
// begin new paragraph
echo "<p>";
// show price
echo "<tr>";
echo "<td>". $Customer->queueName ."</td>";

//add +1 to position in queue to correct 0 position start
$queuePosition = $Customer->queuePosition=$Customer->queuePosition+1;
echo "<td style='text-align:center;'>". $queuePosition ."</td>";

//900 sec = 15min, queue position times 15min 
$estimatedWait = $queuePosition*900;
$estimatedWait = date('H:i:s',$estimatedWait);
echo "<td style='text-align:center;'>". $estimatedWait ."</td>";

echo "<td style='text-align:center;'><a href='#'>Confirm</a></td>";
echo "<td style='text-align:center;'><a href='#'>Delete</a></td>";
echo "</tr>";
// end paragraph
}
// loop ends
?>

Open in new window


Now the cURL works and data is returned, however this bit is supposed to store the info in the variable, but instead it prints it...
$result = curl_exec($ch);

Open in new window


So the HTML I can see on the page looks like this (stripped of the HTML tags etc) so it has basically just printed out the cURL instead of saving it to the variable
Total time for request: 0.12000203132629
<?xml version='1.0' encoding='UTF-8'?>
<User>
<id>1</id>
<email>markus@whyq.eu</email>
<name>Markus Svensson</name>
<phoneNumber>07500933575</phoneNumber>
<Queues>
<Queue>
<queueName>The Pig and Butcher</queueName>
<queuePosition>0</queuePosition>
</Queue>
<Queue>
<queueName>Mews of Mayfair</queueName>
<queuePosition>0</queuePosition>
</Queue>
<Queue>
<queueName>Mews of Mayfair</queueName>
<queuePosition>0</queuePosition>
</Queue>
</Queues>
</User>

Open in new window


The problem then obviously is my XML will have nothing to work with, that part works if I change string to file, so I'm assuming it will work nicely with string as welel.

Very greatful for any help!
0
Comment
Question by:DanteAdmin
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 2
7 Comments
 
LVL 1

Accepted Solution

by:
TWHARRIS earned 500 total points
ID: 38864222
I found a number of questions similar to yours on Google search.
Here is one that may help:

www.forums.devshed.com/php-development-5/curl-curlopt-returntransfer-problem-300420.html
0
 

Author Comment

by:DanteAdmin
ID: 38864517
Hi TWHARRIS

Yes so have I but different in the way that I'm getting my result back, and it's being returned, not as a boolean, but the actual XML I'm after

My problem is it's being printed for no reason I can understand, nowhere in my code am I printing it, it should be stored in the variable.

I've now also noticed that after the XML is printed, nothing else is printed, so the page is effectively being cut off

I ran the
"curl_setopt($ch, CURLOPT_HEADER, 1);"

Open in new window


and the result was :
Content-Length: 454

Which is correct as if I save this to an XML file, which I was doing before with CURL then reading it, the size of that file was 454

If anyone can help, with different set of code even I would be very happy...
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38866304
I believe that the printout occurs because of the echo statement on line 58.  I expect that the XML document is getting created correctly and stored in $result.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:DanteAdmin
ID: 38867015
Hi Ray_Paseur,

No like I written in the first post, nothing is saved to the variable, so that echo command has no data, if I have 10 of those echo commands after each other nothing is printed from them, however it's printed and page stop/breaks after the XML

This is the solution I found after some work:
<?php
    $url = "http://ec2west-1.compute.amazonaws.com:8080/?method=showUser&userPhoneNo=075575";
       
    /**
     * Initialize handle and set options
     */
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);
   
    /**
     * Execute the request and also time the transaction
     */
    $start = array_sum(explode(' ', microtime()));
    $result = curl_exec($ch);
    $stop = array_sum(explode(' ', microtime()));
    $totalTime = $stop - $start;
   
    /**
     * Check for errors
     */
    if ( curl_errno($ch) ) {
        $result = 'ERROR -> ' . curl_errno($ch) . ': ' . curl_error($ch);
    } else {
        $returnCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
        switch($returnCode){
            case 404:
                $result = 'ERROR -> 404 Not Found';
                break;
            default:
                break;
        }
    }
   
    /**
     * Close the handle
     */
    curl_close($ch);
   
    /**
     * Exit the script
     */
?>
	</header>
	<div role="main" id="homepage" style="padding:10px 0 0 0;">
		<center>
		<?php
			echo $_SESSION['clientLogo'];
		?>
		<br/>
		<br/>
		
		<h1>Restaurants you're queuing for</h1>

<table>
	<tr>
		<th>Restaurant</th><th>Position</th><th>Estimated wait</th><th>Action</th><th>&nbsp;</td>
	</tr>	

 


<?
$xml = simplexml_load_string($result);
// loop begins
foreach($xml->Queues->Queue as $Customer)
{
// begin new paragraph
echo "<p>";
// show price
echo "<tr>";
echo "<td>". $Customer->queueName ."</td>";

//add +1 to position in queue to correct 0 position start
$queuePosition = $Customer->queuePosition=$Customer->queuePosition+1;
echo "<td style='text-align:center;'>". $queuePosition ."</td>";

//900 sec = 15min, queue position times 15min 
$estimatedWait = $queuePosition*900;
$estimatedWait = date('H:i:s',$estimatedWait);
echo "<td style='text-align:center;'>". $estimatedWait ."</td>";

echo "<td style='text-align:center;'><a href='#'>Confirm</a></td>";
echo "<td style='text-align:center;'><a href='#'>Delete</a></td>";
echo "</tr>";
// end paragraph
}
// loop ends
?>

Open in new window


So changing this bit:
define('XML_PAYLOAD', '<?xml version="1.0"?><member><name>name</name></member>');
    define('XML_POST_URL', 'http://ec2.eu-west-1.compute.amazonaws.com:8080/AppServlet?method=showUser&userPhoneNo=07575');
       
    /**
     * Initialize handle and set options
     */
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, XML_POST_URL);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 4);
    curl_setopt($ch, CURLOPT_POSTFIELDS, XML_PAYLOAD);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Connection: close'));

Open in new window


To this:
<?php
    $url = "http://ec2-west-1.compute.amazonaws.com:8080/?method=showUser&userPhoneNo=075";
       
    /**
     * Set options
     */
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch,CURLOPT_POST,count($fields));
	curl_setopt($ch,CURLOPT_POSTFIELDS,$fields_string);

Open in new window

0
 

Author Comment

by:DanteAdmin
ID: 38876739
I've requested that this question be closed as follows:

Accepted answer: 0 points for DanteAdmin's comment #a38867015

for the following reason:

After some research I found this solution to work
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 38867701
Hello, DanteAdmin.  By looking at the Activity->Questions on your profile I can see that in the short time you have been a member of Experts Exchange you have asked 6 questions, given one marked-down grade and have deleted 2 questions and now have two more deletions pending.  From this it is fairly easy to conclude that there is little to be gained from trying to help with your questions.  You might want to think about how this affects your online reputation because the points are the only reward your fellow experts get from trying to help you.  And from the look of things, it doesn't appear that there is much chance for any reward at all.
0
 

Author Comment

by:DanteAdmin
ID: 38867733
Hi Ray_Paseur

I'm confused to what you are trying to say... if no ones able to answer or help with a question I should not put the question out there anticipating this ?

Or are you saying I should Accept a solution that isn't anywhere near an answer ? Which I would think to be very misleading if someone is looking for an answer.

In this thread I had one person linking to Google, which I've spent hours trying to figure this out from, so that didn't help me, but is a valid post, and the second from you which I'm greatful for people trying to help but you didn't read what I've written, which was the variable has nothing inside of it.

As far as I'm concerned this is not a Forum for charity points and misleading others in solutions, or a place where difficult questions are not allowed to be asked.

This is a paid service and I would not be happy to find that I pay to see a solution which is not really a solution.

I've linked this post to another post I made, after I had done some research and got a different angle on the problem. I then after even more research myself solved the problem, posted the solution in one thread, and linked the other on to it.

Now if you feel I still did something wrong and should not participate then feel free to let me know and explain to me what I could've done differently

Btw, we've had accounts here for the past 5 years, this is a very recent account.
0

Featured Post

How Do You Stack Up Against Your Peers?

With today’s modern enterprise so dependent on digital infrastructures, the impact of major incidents has increased dramatically. Grab the report now to gain insight into how your organization ranks against your peers and learn best-in-class strategies to resolve incidents.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I was working on a PowerPoint add-in the other day and a client asked me "can you implement a feature which processes a chart when it's pasted into a slide from another deck?". It got me wondering how to hook into built-in ribbon events in Office.
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

730 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question