Parse XML received from a GET request - php

As a part of a school project, i am making a call of the school's api.
Method: GET
Response Format: Xml
Now i use curl to make the web request.
$ch=curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
$data=curl_exec($ch);
curl_close($ch);
Now how do i parse the xml output to get the data i want?
Hope the question is clear

This depends on the exact nature of the content and, moreover, its structure.
The basics are to use DOMDocument (or, alternatively, simplexml, which I dislike as an API) to parse the document, then to use DOM traversal or XPath to find the content you want.
An example might look like this:
$dom = new DOMDocument;
$dom->loadXML($data); // data from cURL request
$xpath = new DOMXPath($dom);
$names = $xpath->query('//student/name'); // find all name elements that are direct children of student elements
foreach ($names as $name) {
echo $name->nodeValue;
}
The exact code you want depends on the structure of the XML and what content you want to get out of it.

Use SimpleXML:
$xml = simplexml_load_string($data);

Take a look at SimpleXML, DOMDocument, XMLParser and XPath. I usually prefer SimpleXML, but as many people, as many opinions...
You will find lots of examples in the documentation to this PHP classes.

assuming that $data contains xml you can use SimpleXML to parse it

Related

Working with CDATA / Soap / PHP

So, I have this xml file:
xml
I use this code to get this xml on php with soap
$response = $clientrepasse->__soapCall("GetSchema", array($paramsrepasse));
$return = $clientrepasse->__getLastResponse()
When I show this $return with my print_r function I got this
return
When I use function var_dump it shows that the $return is a string(40000) positions.
I tried:
$xml = simplexml_load_string($return);
When I print $xml it's empty, I need to transform that string to xml and then to json, or something like that, because I need to work on that xml.
Any help will be appreciated. Thank you and sorry about my english.
Your XML has namespaces. simplexml does not load XMLs into an XML object when it has namespaces. You have to register your namespace to be able to load the XML using simplexml_load_string.
Check the link below:
XML to JSON
XML to JSON
Post XML to get the answer specific to your XML .
You shouldn't need to call __getLastResponse(). It gives you the raw HTTP body as a string, which isn't what you want.
This should be all you need:
$response = $clientrepasse->GetSchema($paramsrepasse);
print_r($response);
You don't need to work with XML. $response will be a PHP object that you can work with straight away.
Note that you also don't need to call __soapCall() directly either.

Not able to read aliexpress.com via php

I'm trying to read aliexpress.com deals page via php. I'm not able to get the details of the page in output.
Is there a way I can get the details.
Below is the code.
<?php
include('simple_html_dom.php');
$url = 'http://activities.aliexpress.com/superdeals.php';
$xml = file_get_html($url);
//$file = 'output1.txt';
$element = $xml;
echo $element;
?>
This website used AJAX
There are two solutions :
- Make the same request as Javascript
- Using a tool like Phantomjs
If you look at requests, you will find easily that a GET request is made and return all information in JSON.
So you need to find by yourself the link or use third party library + tools.
EDIT:
You can use your web browser to get the link (I don't give you it because i think stackoverflow is not for that) with firebug or if you're using chrome, in network tab search for the JSON.
$url = "....";
$str = file_get_contents($url);
if($str) {
$json = json_decode($str, true); // json is an array
// ... do what you need
}
I recommend to use curl instead of file_get_contents for many reasons.
Or you can use Phantomjs (it's really more difficult) and get a "HTML snapshot" and then use DOM or XPATH to get what you need, but you must run Phantomjs and use a third party library for communicate with it.

check youtube video is embeddable <yt:noembed> via xml

I have following link http://gdata.youtube.com/feeds/api/videos/tYMYv1zsAxE and it return an xml file in which is located noembed tag in case the video is not embeddable.
i want to create a loop on list of videos to check which is embeddable and which is not.
Based on your clarification, it sounds like you're asking a question about parsing XML. Here's an alternative: get back JSON, and parse that. You can make a request like
http://gdata.youtube.com/feeds/api/videos/tYMYv1zsAxE?v=2&alt=jsonc&prettyprint=true
and then look at the data->accessControl->embed element within the JSON response.
Or, you know, just parse and access the YouTube API XML exactly like you'd parse the XML from any other source. There's nothing magic going on with the YouTube API XML.
$vidID = "tYMYv1zsAxE";
$url="http://gdata.youtube.com/feeds/api/videos/$vidID?v=2&alt=jsonc&prettyprint=true";
$json = file_get_contents($url, true);
$json_output = json_decode($json);
echo $json_output->data->accessControl->embed;
Simple way to check if youtube video is embeddable.
Thanks to #Jeff Posnick

Use php simpleXML to sort some nodes in a soap request? XSLT?

How can I apply XLST to a SOAP request using PHP simpleXML and XLST? This seems absent in the docs as far as simpleXML's implimentation of the XSLT processor. It has XPATH, but that can't really address my issue of sorting nodes after I get the request...
Any help appreciated
Not SimpleXML:
$xmldoc = new DOMDocument();
$xmldoc->load("*.xml");
$xsltproc = new XSLTProcessor();
$xsltproc->importStylesheet("*.xsl");
$resultdoc = $xsltproc->transformToDoc($xmldoc);

simplexml help how do I parse this?

I haven't done any xml projects, so I'm not quite sure what to do with this data...
I'm using curl to make a request to salesforce, and they give me back a response that I need to parse. I want to use simplexml. Here's part of the response:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<loginResponse>
<result>
<metadataServerUrl>
https://na6-api.salesforce.com/services/Soap/m/18.0/
</metadataServerUrl>
<passwordExpired>
false
</passwordExpired>
<sandbox>
false
</sandbox>
<serverUrl>
https://na6-api.salesforce.com/services/Soap/u/18.0/
</serverUrl>
<sessionId>
!AQ4AQLtDIqY.
</sessionId>
<userId>
</userId>
<userInfo>
<accessibilityMode>
false
</accessibilityMode>
<currencySymbol>
$
</currencySymbol>
<orgDefaultCurrencyIsoCode>
USD
</orgDefaultCurrencyIsoCode>
<orgDisallowHtmlAttachments>
false
</orgDisallowHtmlAttachments>
<orgHasPersonAccounts>
false
</orgHasPersonAccounts>
<organizationId>
</organizationId>
<organizationMultiCurrency>
false
</organizationMultiCurrency>
<organizationName>
Ox
</organizationName>
<profileId>
sdfgsdfg
</profileId>
<roleId>
sdfgsdfg
</roleId>
<userDefaultCurrencyIsoCode xsi:nil="true"/>
<userEmail>
####gmail.com
</userEmail>
<userFullName>
### ###
</userFullName>
<userId>
asdfasdf
</userId>
<userLanguage>
en_US
</userLanguage>
<userLocale>
en_US
</userLocale>
<userName>
asdfasdf#gmail.com
</userName>
<userTimeZone>
America/Chicago
</userTimeZone>
<userType>
Standard
</userType>
<userUiSkin>
Theme3
</userUiSkin>
</userInfo>
</result>
</loginResponse>
</soapenv:Body>
</soapenv:Envelope>
Anyway, I expected to feed that stuff (we'll call it data) into
$results = simplexml_load_string($data);
var_dump($results);
And that would give me all the data back... and then to access specific parts, it would be $results->body->loginResponse->blah->blah...
But It's not giving me that, it's not really giving me anything back, just an empty simple xml object...
So one website made me think I might need an XSLT to read this correctly.
Or something else made me think it's because I don't have at the top.
Help!
You can use SimpleXML but it's not quite as simple as you hope due to the use of namespaces (e.g. soapenv). Look into using SimpleXMLElement::children like:
$sxe = new SimpleXMLElement($data);
$login_response = $sxe->children('soapenv', TRUE)->Body->children('', TRUE)->loginResponse->result;
// Now that we have the <loginResponse> lets take a look at an item within it
echo $login_response->userInfo->userEmail;
Finally, and importantly, have you had a look at salesforce's tools & examples?
SimpleXML needs a special treatment for namespaced XML (ref.)
Mate,
Name spaces usually require you to make a call using children to return the namespaced elements. I would recommend using a soap client like php soapclient, but since I've never used it before there is one other possible option.
$results = simplexml_load_string($data);
$xml = $results->children('http://schemas.xmlsoap.org/soap/envelope/');
var_dump($xml);
I believe that's how it works.
For what it's worth, you may find you have an easier time using a PHP SoapClient for this task. O'Reilly has a good tutorial on PHP SOAP.
Also checkout the PHP Toolkit for making SOAP calls to Salesforce.com
I try to follow the syntax by salathe. But children('soapenv', TRUE) doens't work for me, Jason's children('http://schemas.xmlsoap.org/soap/envelope/') work.
Therefore, to read the field value CreatedDate in Salesforce Outbound Message, I need following code:
$rcXML->children('http://schemas.xmlsoap.org/soap/envelope/')->Body->children('http://soap.sforce.com/2005/09/outbound')->notifications->Notification->sObject->children('urn:sobject.enterprise.soap.sforce.com')->CreatedDate
To help you understand how it work, I write a post with sames code and xml which shall be easier to understand.
http://amigotechnotes.wordpress.com/2013/11/16/parse-xml-with-namespace-by-simplexml-in-php/
Parsing soap responses with SimpleXML has a brilliant and concise example of multi-namespace XML parsing.
For anyone wanting to get at the RateResponse from the UPS Rating API, here's how :
// $client is your SoapClient object
$dom = new DOMDocument;
$dom->loadXML($client->__getLastResponse());
$xml = simplexml_load_string($dom->saveXML(), NULL, NULL, 'http://schemas.xmlsoap.org/soap/envelope/');
$RateResponse = $xml->xpath('/soapenv:Envelope/soapenv:Body')[0]->children('rate', true)->RateResponse;
foreach($RateResponse->RatedShipment as $RatedShipment) {
print_r((array)$RatedShipment);
}
For SAOP request, we can parse easily with a short code by replacing the SOAP-ENV: tag with blank
$response = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns="urn:partner.soap.sforce.com" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>';
$response = html_entity_decode($response);
$response = str_replace(['soapenv:', 'ns1:', ':ns1', 'SOAP-ENV:'], ['', '', '', ''], $response);
$objXmlData = simplexml_load_string($response);

Categories