Parse XML from python script with in php - php

I'm using a python script from with in php to call some xml date from a c# server. When I pass it through simplexml_load_string to parse my data. The python script is called for a few different things, but for one of the calls it gives me
Warning: simplexml_load_string(): Entity: line 1: parser error : StartTag: invalid element name
My PHP is:
$output = exec("python Auth.py -M authenticate -p 17df30b0-37c1-4ebf-b45e-39353bd971a9 -P 5b9abe609e1ab31555562dd959fc050d");
$xml = simplexml_load_string($output, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
My Python is:
params = urllib.urlencode(data);
conn = httplib.HTTPConnection("localhost", 8003);
conn.request("POST", path, params)
response = conn.getresponse()
print response.read();
And my XML is:
<?xml version="1.0"?>
<ServerResponse>
<Result>Success</Result>
<Token>25027fc3-e3c9-46a8-a1b7-5d217fecfe2c</Token>
</ServerResponse>
I can run my Python script from my Ubuntu command line just fine and I wrote the output into a PHP file as XML data and it worked fine on parsing it.
So I don't know what's wrong. Can anybody help?

You are only capturing the last line of the Python print when assigning exec() to a variable. And this last line is not sufficient to create a SimpleXMLElement with simplexml_load_string.
Instead, pass the output stream into an array using the additional output and return_var arguments of PHP's exec(). Once you receive the $output array, iterate through it to build an XML string:
exec("python Auth.py -M authenticate -p 17df30b0-37c1-4ebf-b45e-39353bd971a9" .
" -P 5b9abe609e1ab31555562dd959fc050d", $output, $return_var);
$strXML = '';
foreach ($output as $line) {
$strXML = $strXML . $line;
}
$xml = simplexml_load_string($strXML, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Related

Parsing Mixed XML and HTML with php

I am doing a curl request and getting the following back:
//....curl stuff....//
$result = curl_exec($curl);
curl_close ($curl);
print_R($result);
<html><body onload="if (parent.submitterLoaded)
parent.submitterLoaded();">{"AuthenticationType":0,
"DateDisplayFormat":1, "SystemURL":"https://rmm.server.com",
"Username”:”user”, "UserID":"12205_1", "Error":"", "Success":true,
"ClientID":1, "SessionGuid":"9eb91231b04-feca-4704-b445-
cc5b369581e3", "tag":"", "LastRequestDateTime":"636421428277379996"}
</body></html><?xml version="1.0" encoding="utf-8"?><soap:Envelope
xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body>
<LoginResponse xmlns="http://Iris.net" /></soap:Body></soap:Envelope>
I have tried xml_parser_create and
$xml = simplexml_load_string($xmlstring);
$json = json_encode($xml);
$array = json_decode($json,TRUE);
and i get a garbled mess in return.
Warning: simplexml_load_string(): Entity: line 1: parser error : XML
declaration allowed only at the start of the document in
/var/www/cron/billing/test.php on line 68
PHP Warning: simplexml_load_string(): b6-bd4dd8a0760b",
"LastRequestDateTime":"636421426011959977"}</body></html><?xml in
/var/www/cron/billing/test.php on line 68
PHP Warning: simplexml_load_string():
^ in /var/www/cron/billing/test.php on line 68
I can see what appears to be some json at the {"Keys" area of the response. How can i parse this correctly?
What other info do you need to help answer question?
The first warning indicate the parser doesn't like the second part <?xml version... So get rid of it:
$result = substr($result, 0, strpos($result, '<?xml version'));
Then to pull out the JSON string, use:
$jsonString = (string) simplexml_load_string($result)->body;
$array = json_decode($jsonString);
extract the json with DOMDocument, and parse it with json_decode
$domd=#DOMDocument::loadHTML($response);
$json_data=json_decode(trim($domd->getElementsByTagName("body")->item(0)->textContent));
now the stuff in the json can be accessed like $UserID=$json_data->UserID;, ... and the stuff in the HTML can be accessed in $domd, like $loginResponse=$domd->getElementsByTagName("LoginResponse")->item(0)->textContent; - didn't see anything useful in the html other than the json, though..

SaveXml in php returning empty string

I have the following xml :
<assumption_list>
<assumption name="test" id="23" description="test1" is_shared="no">
<watchlists>
<watchlist globalissuer="koolwater" prepayrate="5" prepaytype="CPR" defaultrate="5" defaulttype="CDR" lossrate="7" lagmonths="2"/>
</watchlists>
</assumption>
</assumption_list>
I load the following received from a jsp call in php as DOMDocument
I am trying the get the <watchlists> node as a string by using the following code :
$result = $xmlDoc->getElementsByTagName('watchlists');
$strxml='';
foreach($result as $element)
{
print_r(simplexml_import_dom($element));
$strxml = $xmlDoc->saveXML($element);
var_dump($strxml);
}
I do see my print_r(simplexml_import_dom($element)); this getting populated but for some reasons i see the empty string after the saveXml operation. Is there something wrong with the current implementation.
I am trying to get the xml string representation so that i can pass the xml string to c# dll used by php application
If you want to output the xml string representation, you can use a simple htmlentities() on this one. Consider this example: Sample Output
$xmlDoc = '<assumption_list> <assumption name="test" id="23" description="test1" is_shared="no"> <watchlists> <watchlist globalissuer="koolwater" prepayrate="5" prepaytype="CPR" defaultrate="5" defaulttype="CDR" lossrate="7" lagmonths="2"/> </watchlists> </assumption></assumption_list>';
$xmlDoc = simplexml_load_string($xmlDoc);
$result = $xmlDoc->assumption->watchlists->watchlist;
// echo $result->asXML(); // output as xml
echo htmlentities($result->asXML()); // output as xml string

Parsing XML data from URL variable in PHP and WordPress

I have a PHP page that a service sends out a notice when a donation is made. My PHP page is supposed to grab the XML contents and parse it out for processing.
The service sends the following format:
http://myserver.com/myphp.com?details= xml data
I have the following code listening for this post:
//Load xml from post
$data = file_get_contents('php://input');
$xmlData = simplexml_load_string($data);
//grab mobile number to query mgive for user info
$mnumb= $xmlData->MobileNumber;
$mnumb=ltrim($mnumb,'1');
I am getting the following error when the service sends out the notice.
Warning: simplexml_load_string() [function.simplexml-load-string]: Entity: line 1: parser error : Start tag expected, '<' not found in
what am I missing or coding wrong?
12-18-2013 855cst
Thanks ThW.. Progress is being made.
I used your suggestion #2 to get the data.
When I do a print_r(xmlData), I get no output on the screen. However, when using chrome developer tool, I get the following output:
data=%3C%3Fxml+version%3D%221.0%22+encoding%3D%22utf-8%22%3F%3E%3CGetDonationStatusResult+xmlns%3Axsi%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema-instance%22+xmlns%3Axsd%3D%22http%3A%2F%2Fwww.w3.org%2F2001%2FXMLSchema%22%3E%3CResultCode+%3E0%3C%2FResultCode%3E%3CResultText+%2F%3E%3CRecordID+%3E0%3C%2FRecordID%3E%3CMobileNumber+%3E12142911111%3C%2FMobileNumber%3E%3CCarrierID+%3E31002%3C%2FCarrierID%3E%3CCarrierName+%3EAT%26amp%3BT+Wireless%3C%2FCarrierName%3E%3CDonationStatus+%3EUserAccepted%3C%2FDonationStatus%3E%3CMobileTransactionID+%3E62622731%3C%2FMobileTransactionID%3E%3CDonationMsgGUID+%3E9c17d57f-b54e-488a-8cf5-1c658d1aa618%3C%2FDonationMsgGUID%3E%3CCampaignID+%3E20409%3C%2FCampaignID%3E%3CShortCode+%3E27722%3C%2FShortCode%3E%3CMsgTime+%3E2013-12-17T12%3A53%3A18%3C%2FMsgTime%3E%3CMessageText+%3ELIBERIA+WAP%3C%2FMessageText%3E%3C%2FGetDonationStatusResult%3E&*
You can see MobileNumber is sent. But, when I echo $mnumb, I get no output. Am I missing something in my use of simplexml_load_string($data); to grab the MobileNumber?
It is not clear where you get the xml data from.
Read from the detail parameter in the url $xml = $_GET['detail'];
Read from the data parameter in the url $xml = $_GET['data'];
Read from the data parameter in the request body (post) $xml = $_POST['data'];
Read the raw post data $xml = file_get_contents("php://input");
Try to var_dump() the data:
var_dump($_GET, $_POST);
After you got the XML into a variable use DOM + Xpath to extract values from it:
$xml = <<<'XML'
<?xml version="1.0" encoding="utf-8"?>
<GetDonationStatusResult xmlns:xsi="w3.org/2001/XMLSchema-instance" xmlns:xsd="w3.org/2001/XMLSchema">
<ResultCode >0</ResultCode>
<ResultText />
<RecordID >0</RecordID>
<MobileNumber >19191112222</MobileNumber>
<CarrierID >31002</CarrierID>
<CarrierName >AT&T Wireless</CarrierName>
<DonationStatus >UserAccepted</DonationStatus>
<MsgTime >2013-12-17T20:53:05</MsgTime>
<MessageText >LIBERIA WAP</MessageText>
</GetDonationStatusResult>
XML;
$dom = new DOMDocument();
// try to load the xml
if ($dom->loadXml($xml)) {
$xpath = new DOMXpath($dom);
// read the first MobileNumber element as string
var_dump(
$xpath->evaluate('string(//MobileNumber)')
);
}
Output:
string(11) "19191112222"
Live Result

How do I parse an XML file with SimpleXMLElement and multiple namespaces?

I have an XML file that looks like the example on this site: http://msdn.microsoft.com/en-us/library/ee223815(v=sql.105).aspx
I am trying to parse the XML file using something like this:
$data = file_get_contents('http://mywebsite here');
$xml = new SimpleXMLElement($data);
$str = $xml->Author;
echo $str;
Unfortunately, this is not working, and I suspect it is due to the namespaces. I can dump the $xml using asXML() and it correctly shows the XML data.
I understand I need to insert namespaces somehow, but I'm not sure how. How do I parse this type of XML file?
All you need is to register the namespace
$sxe = new SimpleXMLElement($data);
$sxe->registerXPathNamespace("diffgr", "urn:schemas-microsoft-com:xml-diffgram-v1");
$data = $sxe->xpath("//diffgr:diffgram") ;
$data = $data[0];
echo "<pre>";
foreach($data->Results->RelevantResults as $result)
{
echo $result->Author , PHP_EOL ;
}
Output
Ms.Kim Abercrombie
Mr.GustavoAchong
Mr. Samuel N. Agcaoili
See Full code In Action

when using XML parse, is the xml resource the object you access?

I dont seem to quite understand how xml_parse works. What i was doing was getting the contents of the xml file, create a parser, and pass it into xml_parse(). I dont know what to do after that. I was thinking that in my case, $xml was the array i can now iterate through. I was trying to see how i would parse my data.
$fp = file_get_contents("memberdata.xml");
echo "pre-create";
$xml = xml_parser_create();
echo "pre-parse";
$status = xml_parse($xml,$fp);
if(!$status){
die("Error parsing data from $fp into $xml");
}
echo "pre XML posting";
echo "<br />".$xml."<br />";
print_r($xml);
xml_parser_free($xml);
I cant seem to figure out how to access this.
Sample xml data is as follows:
<currentTime>2012-09-05 03:43:25</currentTime>
<result>
<rowset name="members" key="characterID" columns="characterID,name,startDateTime,baseID,base,title,logonDateTime,logoffDateTime,locationID,location,shipTypeID,shipType,roles,grantableRoles">
<row ..>
</rowset>
</result>
<cachedUntil></cashedUntil>
Instead of using the base tools, using one of the toolkits, SimpleXML will alleviate a lot of the frustrations. The answer to this question is redone using SimpleXML.
$fp = file_get_contents("memberdata.xml");
$eve = new SimpleXMLElement($fp);
$cols = $eve->{'result'}->rowset['columns'];
//I put result in {} because result is a special character in php.
$cols = explode(",",$cols);
foreach ($cols as $c){
echo "".$c."<br />";
}
//output is printed to screen

Categories