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
Related
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
I'm trying to parse an xml data that I'm getting via an api call. I can use file_get_contents to read into a string but simpleXML_load_string seems to fail to read it. I can save it to a file and then simpleXML_load_file works. But I would rather not write the contents to a file. I can't seem to understand how to use DOM or XMLParse with this either. I'm new to PHP and parsing XML. The output data from the api call is below.
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
<LargestGiftLow>0</LargestGiftLow>
<LargestGiftHigh>0</LargestGiftHigh>
<EstimatedCapacityRange>I - $15,000 - $24,999</EstimatedCapacityRange>
<EstimatedCapacity>20452</EstimatedCapacity>
<RealEstateEst>270073</RealEstateEst>
<RealEstateCount>1</RealEstateCount>
<LikelyMatchesCount>0</LikelyMatchesCount>
<LikelyMatchesTotal>0</LikelyMatchesTotal>
<FndBoard></FndBoard>
<GSBoard></GSBoard>
<PoliticalLikelyCount>0</PoliticalLikelyCount>
<PoliticalLikelyTotal>0</PoliticalLikelyTotal>
<BusinessRevenues>0</BusinessRevenues>
<SECStockValue>0</SECStockValue>
<SECInsider></SECInsider>
<MarketGuide></MarketGuide>
<IRS990PF></IRS990PF>
<RealEstateTrust></RealEstateTrust>
<MarketGuideComp>0</MarketGuideComp>
<MarketGuideOptions>0</MarketGuideOptions>
<BusinessAffiliation></BusinessAffiliation>
<Pension></Pension>
<PensionAssets>0</PensionAssets>
<CorpTech></CorpTech>
<Pilot></Pilot>
<AirplaneOwner></AirplaneOwner>
<Boat></Boat>
<submit_time>2014-03-11 15:48:45</submit_time>
</Search>
Figured out that the issue was that what I was seeing in the browser was actually a php output with html_entiity encoded. I was able to process it with the code below which let me load it with simplexml.
$rawxml = html_entity_decode($rawxml);
$rawxml = str_replace(array(' ', "<pre>"), '', $rawxml);
$rawxml = utf8_encode($rawxml);
$xml = simplexml_load_string($rawxml);
If you XML is in a file use
simplexml_load_file
if you have it in a string use
simplexml_load_string
Then you can use the following code to access it.
<?php
$yourxml = simplexml_load_file('your.xml');
echo $yourxml->search[0]->DS_Rating;
?>
This would then output
DS3
to the browser via the 'echo' in your code. I hope this points you in the correct direction.
Try to use this:
$xml = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8" ?>'.$yourXMLString);
In DOM you load the XML into a DOMDocument and create a DOMXpath instance for it.
$dom = new DOMDocument();
$dom->loadXml($xmlString);
//$dom->load($xmlFile);
$xpath = new DOMXpath($dom);
DOMXpath::evaluate() is used to fetch data from the DOM.
$rating = $dom->evaluate('string(/Search/DS_Rating)');
An Xpath expression like /Search/DS_rating always returns a node list. You can use foreach() to iterate it. The string() function in Xpath takes the first node from the list and casts it into a string. If here is not node in the list the result is an empty string.
$xmlString = <<<'XML'
<Search>
<DS_Rating>DS3</DS_Rating>
<Overall>17.5</Overall>
</Search>
XML;
$dom = new DOMDocument();
$dom->loadXml($xmlString);
$xpath = new DOMXpath($dom);
var_dump(
$xpath ->evaluate('string(/Search/DS_Rating)')
);
Output: https://eval.in/118921
string(3) "DS3"
I have found very little documentation on this API so I have came here with the hopes that someone knows how to use this thing. When I try this nothing shows up. For now I am just trying to display the title of the first listing. Here is my code:
<?php
$url = "http://api.oodle.com/api/v2/listings?key=MYKEY®ion=sf&category=sale/electronics&q=ipod";
$response = file_get_contents($url);
echo $response->element[0]->title;
?>
And here is a link to the XML: http://api.oodle.com/api/v2/listings?key=TEST®ion=chicago&category=vehicle/car
Thanks!
You have to parse the XML before you can access it like that.
Something like the following (untested!)
<?php
$url = "http://api.oodle.com/api/v2/listings?key=MYKEY®ion=sf&category=sale/electronics&q=ipod";
$response = file_get_contents($url);
$xmlDoc = new SimpleXMLElement($response);
echo $xmlDoc->element[0]->title;
?>
In this example I'm using SimpleXML.
In simpler terms, by doing $xmlDoc = new SimpleXMLElement($response) we're telling PHP that $response contains XML that should be parsed into structures that can be programmatically accessed.
In this case $xmlDoc becomes a SimpleXMLElement object, that you can use as per documentation: http://php.net/manual/en/class.simplexmlelement.php
How to parse this type of files in php
I have tried using
<?php
$xml ="office.xml";
// get first book title
$title=$xml->featureMember->AA_OFFICE;
// show title
echo $title;
echo '<br/>';
?>
if iam using gml:featuremember instead of featuremember i am getting an error in syntax
if i use featuremember iam getting ) Notice: Trying to get property of non-object
<gml:boundedBy>
<gml:null>unknown</gml:null>
</gml:boundedBy>
<gml:featureMember>
<kgp:AA_OFFICE fid="AA_OFFICE.1">
<kgp:the_geom>
<gml:Point srsName="http://www.opengis.net/gml/srs/epsg.xml#32645">
<gml:coordinates xmlns:gml="http://www.opengis.net/gml" decimal="." cs="," ts=" ">643630.3815,2498825.0741</gml:coordinates>
</gml:Point>
</kgp:the_geom>
<kgp:Name>MANMARK EXPORT PVT LTD</kgp:Name>
<kgp:Type/>
<kgp:Plot_No>55</kgp:Plot_No>
<kgp:Block_Name>AA</kgp:Block_Name>
</kgp:AA_OFFICE>
</gml:featureMember>
You are trying to use a string as an object. You have to create some form of XML Parsing object first. For example,
$xmlDoc = new DOMDocument();
$xmlDoc->load("office.xml");
More information
or
$xml = simplexml_load_file("office.xml");
More information
try to debug your xml
libxml_use_internal_errors(true);
$xml = simplexml_load_file("office.xml");
var_dump(libxml_get_errors());
Hello I have an api response in xml format with a series of items such as this:
<item>
<title>blah balh</title>
<pubDate>Tue, 20 Oct 2009 </pubDate>
<media:file date="today" data="example text string"/>
</item>
I want to use DOMDocument to get the attribute "data" from the tag "media:file". My attempt below doesn't work:
$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
$nodes = $feeditem->getElementsByTagName('media:file');
$linkthumb = $nodes->item(0)->getAttribute('data');
}
What am I doing wrong? Please help.
EDIT: I can't leave comments for some reason Mark. I get the error
Call to a member function getAttribute() on a non-object
when I run my code. I have also tried
$nodes = $feeditem->getElementsByTagNameNS('uri','file');
$linkthumb = $nodes->item(0)->getAttribute('data');
where uri is the uri relating to the media name space(NS) but again the same problem.
Note that the media element is of the form not I think this is part of the problem, as I generally have no issue parsing for attibutes.
The example you provided should not generate an error. I tested it and $linkthumb contained the string "example text string" as expected
Ensure the media namespace is defined in the returned XML otherwise DOMDocument will error out.
If you are getting a specific error, please edit your post to include it
Edit:
Try the following code:
$xmldoc = new DOMDocument();
$xmldoc->load('api response address');
foreach ($xmldoc->getElementsByTagName('item') as $feeditem) {
$nodes = $feeditem->getElementsByTagName('file');
$linkthumb = $nodes->item(0)->getAttribute('data');
echo $linkthumb;
}
You may also want to look at SimpleXML and Xpath as it makes reading XML much easier than DOMDocument.
Alternatively,
$DOMNode -> attributes -> getNamedItem( 'MyAttribute' ) -> value;