Solved

PHP, cURL and XML

Posted on 2013-02-07
7
526 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
  • 4
  • 2
7 Comments
 
LVL 1

Accepted Solution

by:
TWHARRIS earned 500 total points
Comment Utility
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
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:DanteAdmin
Comment Utility
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
Comment Utility
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 108

Expert Comment

by:Ray Paseur
Comment Utility
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
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

Introduction In my previous article (http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SSIS/A_9150-Loading-XML-Using-SSIS.html) I showed you how the XML Source component can be used to load XML files into a SQL Server database, us…
The Confluence of Individual Knowledge and the Collective Intelligence At this writing (summer 2013) the term API (http://dictionary.reference.com/browse/API?s=t) has made its way into the popular lexicon of the English language.  A few years ago, …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to count occurrences of each item in an array.

744 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now