using PHP for xml post

Discussion in 'Programming' started by mthacker, Jan 23, 2008.

  1. #1
    I am working on a project to pull data from a remote server using xml posting. I can get the xml file created but am unable to then read and post the file to the url. Here is the code I have to this point

    $xml_dec = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";

    $rootELementStart = "<REQUEST_GROUP MISMOVersionID='2.1'>";

    $rootElementEnd = "</REQUEST_GROUP>";

    // $xml_doc = $xml_dec;

    $xml_doc .= $rootELementStart;

    $xml_doc .= "<RECEIVING_PARTY _Name='".$ProviderID."' />";

    $xml_doc .= "<SUBMITTING_PARTY _Name='Liberty Mortgage Funding' />";

    $xml_doc .= "<REQUEST InternalAccountIdentifier='".$InternalAcctID."' LoginAccountIdentifier='".$AcctID."' LoginAccountPassword='".$AcctPassword."' RequestDateTime='".$today."' >";

    $xml_doc .= "<REQUEST_DATA>";

    $xml_doc .= "<CREDIT_REQUEST LenderCaseIdentifier='".$LenderCaseID."' MISMOVersionID='2.1' RequestingPartyRequestedByName='".$session_username."'>";

    $xml_doc .= "<CREDIT_REQUEST_DATA BorrowerID='".$BorID."' CreditReportIdentifier='' CreditReportRequestActionType='Submit' CreditRequestType='Single'>";

    $xml_doc .= "<CREDIT_REPOSITORY_INCLUDED _EquifaxIndicator='Y' _ExperianIndicator='Y' _TransUnionIndicator='Y' />";

    $xml_doc .= "<CREDIT_SCORE_MODEL_NAME _Type='EquifaxBeacon' />";

    $xml_doc .= "<CREDIT_SCORE_MODEL_NAME _Type='TransUnionEmpirica' />";

    $xml_doc .= "</CREDIT_REQUEST_DATA>";

    $xml_doc .= "<LOAN_APPLICATION>";

    $xml_doc .= "<BORROWER BorrowerID='Borrower' _FirstName='New' _LastName='Aold' _MiddleName='' _NameSuffix='' _SSN='424384212'>";

    $xml_doc .= "<_RESIDENCE BorrowerResidencyType='Current' _City='Jeffersonville' _PostalCode='47130' _State='IN' _StreetAddress='728 Briscoe Drive' />";

    $xml_doc .= "</BORROWER>";

    $xml_doc .= "</LOAN_APPLICATION>";

    $xml_doc .= "</CREDIT_REQUEST>";

    $xml_doc .= "</REQUEST_DATA>";

    $xml_doc .= "</REQUEST>";

    $xml_doc .= $rootElementEnd;

    $default_dir = "XMLFiles/";

    $default_dir .= $xmlfileName .".xml";

    $fp = fopen($default_dir,'w');


    $write = fwrite($fp,$xml_doc);


    //Attempt to post the previously created xml file to the equifax url provided

    $protocol = 'HTTP/1.1';
    $URL = 'the url;
    $pathToFolder = 'the path';
    $contentType = 'text/xml';


    $requestBody = $xml_doc;
    echo $requestBody;

    the var $xml_doc does correctly work when creating the xml file, but when I try to read the file into the $requestBody variable the only line that comes through is
    <_RESIDENCE BorrowerResidencyType='Current' _City='Jeffersonville' _PostalCode='47130' _State='IN' _StreetAddress='728 Briscoe Drive' />

    what am I doing wrong? This is my first experience with xml posting so I'm really lost on this one. Any help would be greatly appreciated.
     
    mthacker, Jan 23, 2008 IP
  2. sutuicom

    sutuicom Peon

    Messages:
    103
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #2
    you need use " instead of ' for the xml attribute.
     
    sutuicom, Jan 23, 2008 IP
  3. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    could you show an example of using that command, I can't find anything on it?
     
    mthacker, Jan 24, 2008 IP
  4. Estevan

    Estevan Peon

    Messages:
    120
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    0
    #4
    hello
    the problem is you try read by browser and no correct header sent from document have 2 solutions
    add correct header in top of your file
    <?php
    header("Content-type: text/xml"); ... here your code

    or echo htmlentities($requestBody); Convert all applicable characters to HTML entities

    all work choose one !

    best
     
    Estevan, Jan 24, 2008 IP
  5. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Thanks for the previous post, that worked and now I have all of my xml file into the $requestBody var, now my other problem is the actual posting. Most of what I've seen on posting xml is using methods only available in php 5.0 or greater. Our server is running php 4.4.4 w/o Curl, which I really don't want to get into if I don't have to(hate making config changes on servers if avoidable) Anyone know any good sites or examples on posting the xml to a remote url? Thanks in advance
     
    mthacker, Jan 24, 2008 IP
  6. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #6
    well after another step of testing I have noticed an issue, if I use the second option given above and convert everything to html entities then I get the entire xml file into the $requestbody var, but if I try to just put the header in front of the xml code then I get an error saying that
    "Only one top level element is allowed in an XML document."

    But I only get that error if I leave in the lines:
    $xml_dec = "<?xml version=\"1.0\" ?>";
    $xml_doc = $xml_dec;

    Not sure what is going on with this, but I'm sure that line needs to be in the xml doc so not sure how to get around this.
     
    mthacker, Jan 24, 2008 IP
  7. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #7
    Now I'm on to a new problem, I have created, and read the xml file into a variable and am attempting to pass it into a method to post the file contents to the server. Here's the code I have, as you can see I have echoes on almost every line to try and find out where the process is stopping, but when I got to trying to echo out the $fp variable I noticed that it is empty, which is obviously why I'm not getting anything in the post.

    function postXMLToURL ($server, $path, $xmlDocument) {
    $contentLength = strlen($xmlDocument);
    echo $contentLength;
    $fp = fsockopen($server, 80, $errno, $errstr, 60);
    if (!$fp) {
    echo "$errstr ($errno)<br />\n";
    }
    else
    {
    echo '1.Connection Opened';
    fputs($fp, "POST $path HTTP/1.0\r\n");
    echo '<br>2.Path Established';
    fputs($fp, "Host: $server\r\n");
    echo '<br>3.Server Established';
    fputs($fp, "Content-Type: text/xml\r\n");
    echo '<br>4.Content Header';
    fputs($fp, "Content-Length: $contentLength\r\n");
    echo '<br>5.Content Length';
    fputs($fp, "Connection: close\r\n");
    echo '<br>6.Connection Closed';
    fputs($fp, "\r\n"); // all headers sent
    echo '<br>7.Headers Sent';
    fputs($fp, $xmlSource);
    echo '<br>8.XML file sent';
    echo '<br>$FP='.$fp;
    $result = '';
    while (!feof($fp)) {
    $result .= fgets($fp, 128);
    }
    }

    return $result;
    }

    function getBody ($httpResponse)
    {
    $lines = preg_split('/(\r\n|\r|\n)/', $httpResponse);
    $responseBody = '';
    $lineCount = count($lines);
    for ($i = 0; $i < $lineCount; $i++)
    {
    if ($lines[$i] == '')
    {
    break;
    }
    }
    for ($j = $i + 1; $j < $lineCount; $j++)
    {
    $responseBody .= $lines[$j] . "\n";
    }
    return $responseBody;
    }

    $filename = 'Testing.xml';

    $xmlDocument = file_get_contents($filename);
    // echo htmlentities($xmlDocument);

    $result = postXMLtoURL("theServer", "thePath", $xmlDocument);
    echo '<br>10.Prepare to Get Body';
    $responseBody = getBody($result);

    $resultDocument = file_get_contents($responseBody);

    echo htmlentities($resultDocument);


    I get a successful connection with the fsockopen, and the $contentLength var shows the correct length of my xml file yet nothing is getting passed in the $fp var for some reason, what am I missing? any ideas
     
    mthacker, Jan 24, 2008 IP
  8. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #8
    Well I thought I was getting a successful fsockopen connection but after adding some more to my echos I noticed that this is what I get
    The operation completed successfully. (0)

    I don't understand why I'm getting the error now. Not sure what is going on I have the server, path, and xmldocument vars set properly.
     
    mthacker, Jan 24, 2008 IP
  9. Estevan

    Estevan Peon

    Messages:
    120
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    0
    #9
    hello i post a lite code here to help you !

    thisfilesentdatafromserver.php
    change 2 variables
    add here the complete url include the filename.php
    $_URL="http://fullurllocatefilerecievethedata/filedata.php";
    this is the xml created
    $_filename="yourxmlname.xml";
    this is the file sender add more values if need
    curl_setopt($ch, CURLOPT_POSTFIELDS, "mydata=".$xml_doc."&fname=".$_filename."");
    
    <?php
    
    // The XML request to be sent
    $xml_doc .= "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><REQUEST_GROUP MISMOVersionID='2.1'></REQUEST_GROUP>";
    
    
    $xml_doc .= "<RECEIVING_PARTY _Name='".$ProviderID."' />";
    
    $xml_doc .= "<SUBMITTING_PARTY _Name='Liberty Mortgage Funding' />";
    
    $xml_doc .= "<REQUEST InternalAccountIdentifier='".$InternalAcctID."' LoginAccountIdentifier='".$AcctID."' LoginAccountPassword='".$AcctPassword."' RequestDateTime='".$today."' >";
    
    $xml_doc .= "<REQUEST_DATA>";
    
    $xml_doc .= "<CREDIT_REQUEST LenderCaseIdentifier='".$LenderCaseID."' MISMOVersionID='2.1' RequestingPartyRequestedByName='".$session_username."'>";
    
    $xml_doc .= "<CREDIT_REQUEST_DATA BorrowerID='".$BorID."' CreditReportIdentifier='' CreditReportRequestActionType='Submit' CreditRequestType='Single'>";
    
    $xml_doc .= "<CREDIT_REPOSITORY_INCLUDED _EquifaxIndicator='Y' _ExperianIndicator='Y' _TransUnionIndicator='Y' />";
    
    $xml_doc .= "<CREDIT_SCORE_MODEL_NAME _Type='EquifaxBeacon' />";
    
    $xml_doc .= "<CREDIT_SCORE_MODEL_NAME _Type='TransUnionEmpirica' />";
    
    $xml_doc .= "</CREDIT_REQUEST_DATA>";
    
    $xml_doc .= "<LOAN_APPLICATION>";
    
    $xml_doc .= "<BORROWER BorrowerID='Borrower' _FirstName='New' _LastName='Aold' _MiddleName='' _NameSuffix='' _SSN='424384212'>";
    
    $xml_doc .= "<_RESIDENCE BorrowerResidencyType='Current' _City='Jeffersonville' _PostalCode='47130' _State='IN' _StreetAddress='728 Briscoe Drive' />";
    
    $xml_doc .= "</BORROWER>";
    
    $xml_doc .= "</LOAN_APPLICATION>";
    
    $xml_doc .= "</CREDIT_REQUEST>";
    
    $xml_doc .= "</REQUEST_DATA>";
    
    $xml_doc .= "</REQUEST>";
    
    
    $_URL="http://fullurllocatefilerecievethedata/filedata.php";
    $_filename="yourxmlname.xml";
        $ch=curl_init();
    // This is the custom header that needs to be sent to post to your blog.
       // $headers  =  array( "Content-Type: text/xml" );
        curl_setopt($ch, CURLOPT_URL, $_URL);
        curl_setopt($ch, CURLOPT_HEADER, 0); 
        curl_setopt($ch, CURLOPT_POST, 1);
      //  curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, "mydata=".$xml_doc."&fname=".$_filename."");
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
        curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
        curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
        $xml = curl_exec ($ch);
        curl_close ($ch);
    
        echo ($xml);
    
    ?>
    
    
    PHP:
    filedata.php
    this file recieved the data and write don't forgot add chmod 777 in your folder to script able create new files
    
    <?php
    // DISPLAY THE DATA SENT 
    echo htmlentities($_POST['mydata']);
    // CREATE THE NEW FILE XML
    $fp = fopen($_POST['fname'],'w');
    // WRITE DATA 
    $write = fwrite($fp,$_POST['mydata']);
    fclose($fp);
    ?>
    
    
    PHP:
    i believed this help you
     
    Estevan, Jan 24, 2008 IP
  10. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #10
    I don't believe that the server I am using has curl enabled. I have only been here a few months and am not sure how php was configured originally. Is it difficult to reconfigure and enable curl?
     
    mthacker, Jan 25, 2008 IP
  11. Estevan

    Estevan Peon

    Messages:
    120
    Likes Received:
    8
    Best Answers:
    1
    Trophy Points:
    0
    #11
    Estevan, Jan 25, 2008 IP
  12. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #12
    The site that I'm trying to connect to is a secure site. Will that make a difference if I use curl?
     
    mthacker, Jan 30, 2008 IP
  13. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #13
    I'm currently trying to use fsockopen() command but keep getting error (0) on the connection attempt. Looked at my phpinfo() and found openSSl installed and https was off. Does https have to be turned on in order to post to secure sites?
     
    mthacker, Jan 30, 2008 IP
  14. lephron

    lephron Active Member

    Messages:
    204
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    53
    #14
    It looks like you don't know about the heredoc syntax. It would come in really useful here. Eg:

     
    lephron, Jan 31, 2008 IP
  15. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #15
    I can connect and attempt to post my xml file now, but am getting a response error saying that my xml is not well formed. Can anyone help me out with this, I've ran it through syntax validators and its syntactically correct. Here's the xml file.



    <?xml version='1.0' encoding='UTF-8' ?><REQUEST_GROUP MISMOVersionID='2.1'><RECEIVING_PARTY _Name='999LM01098' /><SUBMITTING_PARTY _Name='Liberty Mortgage Funding' /><REQUEST InternalAccountIdentifier='acctID LoginAccountIdentifier='ID' LoginAccountPassword='Pass' RequestDateTime='2008-01-31 10:37:20' ><REQUEST_DATA><CREDIT_REQUEST LenderCaseIdentifier='caseID' MISMOVersionID='2.1' RequestingPartyRequestedByName='mthacker'><CREDIT_REQUEST_DATA BorrowerID='100252' CreditReportIdentifier='' CreditReportRequestActionType='Submit' CreditRequestType='Single'><CREDIT_REPOSITORY_INCLUDED _EquifaxIndicator='Y' _ExperianIndicator='Y' _TransUnionIndicator='Y' /><CREDIT_SCORE_MODEL_NAME _Type='EquifaxBeacon' /><CREDIT_SCORE_MODEL_NAME _Type='TransUnionEmpirica' /></CREDIT_REQUEST_DATA><LOAN_APPLICATION><BORROWER BorrowerID='Borrower' _FirstName='New' _LastName='Aold' _MiddleName='' _NameSuffix='' _SSN='theSSN'><_RESIDENCE BorrowerResidencyType='Current' _City='Jeffersonville' _PostalCode='47130' _State='IN' _StreetAddress='theAddress' /></BORROWER></LOAN_APPLICATION></CREDIT_REQUEST></REQUEST_DATA></REQUEST></REQUEST_GROUP>


    I'm trying with hard coded data for testing purposes, so I had to remove the data.
     
    mthacker, Jan 31, 2008 IP
  16. westbrooks

    westbrooks Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #16
    Did you find a solution for this issue? I'm actually working on the same issue right now. I'm trying to submit the same XML data to Equifax with php 4.3 and am having problems finding the proper way to handle it. Did you end up using CURL to submit the data?
     
    westbrooks, Apr 29, 2008 IP
  17. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #17
    This whole process was a pain in the behind but I finally did get everything working. To answer your question I did use curl, but my main problem was having single quotes and not double quotes on my variables. So I had to find a way to double quote my variables, as so:

    $xml_doc .= "<RECEIVING_PARTY _Name=\"".$ProviderID."\" />";

    and for hardcoded parts which I don't have many

    $xml_doc .= "<REQUEST_GROUP MISMOVersionID=\"2.1\">";

    now for the curl option it ended up being great all I had to do was go into the php.ini file and uncomment the line for curl and it was ready to run, here's my code that executed the connection and returned my data in an xml file.

    $fp1 = fopen($CreditResponse, "w");

    $ch=curl_init();
    // This is the custom header that specifies following is text/xml format.
    $headers = array( "Content-Type: text/xml" );
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_data);
    curl_setopt($ch, CURLOPT_FILE, $fp1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); //timeout after 30 seconds
    curl_setopt ($ch, CURLOPT_USERAGENT, "User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0)");
    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
    $xmlResponse = curl_exec ($ch);
    //echo $xmlResponse;
    fwrite($fp1,$xmlResponse);
    curl_close ($ch);
    fclose($fp1);
    // echo htmlentities($xmlResponse);

    $xmldata is just the data read from the xml file I created to send

    The worst part of this for me was the step after this where I had to pull the pdf file information out of the cdata tags in order to decode and display the report as a pdf for the user. Need anything else just let me know, hope this helps you out
     
    mthacker, Apr 29, 2008 IP
  18. westbrooks

    westbrooks Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #18
    Thanks for your help and quick response. This looks pretty straight forward, but if I have any questions, I may be back. Thanks again.
     
    westbrooks, Apr 30, 2008 IP
  19. westbrooks

    westbrooks Peon

    Messages:
    4
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #19
    It's been a while. I finally got the test account information from our rep and was able to test my code. I've come to the worst part which is the same issue you had with the pdf file. I tried different ways to do this, but I get a damage/decoding error every time.

    Do you mind me asking how you went about pulling the cdata and decoding it to display the pdf? Thank you for your help in advance.
     
    westbrooks, Jul 15, 2008 IP
  20. mthacker

    mthacker Peon

    Messages:
    25
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #20
    Yeah this was a real pain for me as well, took quite a bit of time and questioning on forums to get it right but here's what I used


    Start by pulling in the data from the response file that you received from the post

    $CreditResponse = "XMLFiles/".$xmlfileName."Response.xml";

    //If file was created save the data and display the pdf report
    $fp5 = fopen($CreditResponse, "r");
    $theSize = filesize($CreditResponse);
    $data = fread($fp5, $theSize);
    fclose($fp5);
    //echo htmlentities($data);

    Then get the contents of the file into a string

    $theFile = file_get_contents($CreditResponse);

    then you have to encode the string data

    $newstring=utf8_encode($theFile);
    //echo $newstring;
    $xmlPath = realpath("XMLFiles/");
    //echo $xmlPath;

    Then the fun part, using the preg_match_all to find the cdata tags and pull everything in between, and then remove all spacing and line feed chars

    $TheData = preg_match_all("/<!\[CDATA\[(.*?)\]\]>/s", $data, $string);
    $string = str_replace("\r\n", "", $string);
    //print_r($string);
    $testing = $string[1][0];
    $testing = str_replace(array("\r", "\n", "\t", " "), "", $testing);
    //echo $testing;

    //Construct PDF name and write data to the report
    $PDFName = $LastName.''.$FirstName.''.$LoanID.'.pdf';
    $filename = "CreditReports/".$PDFName;
    //echo $filename;

    // encode & write data (binary)

    $ifp = fopen($filename, "wb" );
    fwrite( $ifp, base64_decode( $testing ) );
    fclose( $ifp );

    Thats what I ended up with and it works well so far, hope it works for you as well. Good Luck
     
    mthacker, Jul 15, 2008 IP