How to traverse xml in php - php

I am using the following function
function file_get_contents_curl($url) {
$ch = curl_init();
curl_setopt($ch, CURLOPT_AUTOREFERER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
$myTestingUrl = file_get_contents_curl("myUrl");
After I run that function I have
$myTestingUrl =
<?xml version="1.0" encoding="UTF-8"?>
<map>
<entry key="keyName">
<entry key="ActionUrl">http://www.my_actionUrl.com/</entry>
</entry>
</map>
Can you please tell me how can I traverse $myTestingUrl to get the content of entry key "ActionUrl" (http://www.my_actionUrl.com/) in a variable in php?
Thank you!

Try
$xml = simplexml_load_string($myTestingUrl );
$items = $xml->xpath('/map/entry/entry[#key="ActionUrl"]/text()');
echo $items[0];

I prefer #air4x's XPath method but here it is without XPath - for the purpose of showing element and attribute access in SimpleXML:
Codepad demo
$obj = simplexml_load_string($myTestingUrl);
foreach($obj->entry as $entry)
{
if(isset($entry->entry))
{
foreach($entry->entry->attributes() as $key => $value)
{
if($key == 'key' && $value == 'ActionUrl')
{
echo 'ActionUrl is: ' . (string)$entry->entry;
break 1;
}
}
}
}

Related

How to convert <string xmlns="http://tempuri.org/"> to json in php?

I find a problem to convert <string xmlns="http://tempuri.org/"> to json in php, I try to look for an example but fail all.
This is my php script:
public function register() {
$url = 'https://example.com/register';
$post_data="Email=frank#email.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
}
and this is the response :
Please anyone help me to solve this problem.
Thanks
It's a strange idea to send JSON in an XML document, but anyway. Simplest (sensible way) is to load it with SimpleXML and then the JSON is just the text of the root node...
$xml = simplexml_load_string($result);
echo (string)$xml;
should give
[
{
"CreateDate": "123"
}
]
I agree with Nigel's comment that it's strange to embed JSON in XML, but IMO his solution plays a bit fast and loose with the assumed simplicity of the input. Also, DOMDocument and family tend to be a lot easier to use as far as PHP's XML libs go.
$in = <<<_E_
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://tempuri.com/">[
{
"foo": "bar"
}
]</string>
_E_;
$doc = new DomDocument();
$doc->loadxML($in);
$json = $doc->getElementsByTagName('string')->item(0)->nodeValue;
$decoded = json_decode($json, true);
var_dump($json, $decoded);
Output:
string(24) "[
{
"foo": "bar"
}
]"
array(1) {
[0]=>
array(1) {
["foo"]=>
string(3) "bar"
}
}
https://www.php.net/manual/en/book.dom.php
Finally, I find a solution, like this :
public function register() {
$url = 'https://example.com/register';
$post_data="Email=frank#email.com";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded; charset=utf-8'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$xml = simplexml_load_string($result,'SimpleXMLElement',LIBXML_NOCDATA);
header('Content-Type: application/json');
$temp = json_decode($xml);
$json = json_encode($temp[0]);
echo $json;
}
and it works;

"Invalid argument supplied for foreach()" reading XML?

IM gettin: "Invalid argument supplied for foreach()"
in the for each line when trying to read an specific item of the xml
PHP:
$urls="http://www.floatrates.com/daily/usd.xml";
$url= $urls;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$feed = new SimpleXMLElement($data,LIBXML_NOCDATA);
foreach ($feed->channel->item as $item) {
$title = $item->title;
if (preg_match('/ARS/',$title)) {
echo $title;
}
}
$urls = "http://www.floatrates.com/daily/usd.xml";
$url = $urls;
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);
$feed = new SimpleXMLElement($data, LIBXML_NOCDATA);
foreach ($feed->children() as $item) {
if ("item" == $item->getName()) {
$title = $item->title;
if (preg_match('/ARS/', $title)) {
echo $title;
}
}
}
It probably means that $feed does not contain what you expect it to contain, and you are not passing array to foreach Use print_r($feed); to see that it actually contains, and go from there.

print xml response separately for each property

I am trying to convert this XML to array this is the response I am getting from API and I want to get the value of statuscode but I am unable to do it.
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
but when i am using the following code
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
$resultres=xml2ary($result);
echo '<pre>';
print_r($resultres);
The output is
Array
(
[string] => Array
(
[_a] => Array
(
[xmlns] => http://tempuri.org/
)
[_v] => 201234
)
)
How is the result changing? I have used one more technique also but with that also I am not getting the result that is required
Have a look at SimpleXML
<?php
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_FAILONERROR, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 6);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,'RequestData='.$post);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-type: application/x-www-form-urlencoded'));
$result = curl_exec($ch);
/** #var SimpleXMLElement $xml */
$xml = simplexml_load_string($result);
// nice, use SimpleXMLElement object
var_dump($xml);
// not nice, use array instead
var_dump((array) $xml);
Just make sure the XML response you're getting from the API is the same you have posted above. Here it is again for reference:
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
Here is an example without cURL, just add it to a file and run it from the terminal:
<?php
$xmlString = <<<XML
<?xml version='1.0' encoding='utf-8' standalone='no'?>
<REGISTRATIONRESPONSE>
<STATUSCODE>20</STATUSCODE>
<STATUS>1234</STATUS>
</REGISTRATIONRESPONSE>
XML;
$xml = simplexml_load_string($xmlString);
// everything
var_dump($xml);
// independent values
var_dump((string) $xml->STATUSCODE);
var_dump((string) $xml->STATUS);
// now with arrays
$array = (array) $xml;
// everything
var_dump($array);
// independent values
var_dump($array['STATUSCODE']);
var_dump($array['STATUS']);
// want to print it?
echo sprintf('Registration responded with status code %d and status %d', $xml->STATUSCODE, $xml->STATUS) . PHP_EOL;
echo sprintf('Registration responded with status code %d and status %d', $array['STATUSCODE'], $array['STATUS']) . PHP_EOL;
If the XML is coming through, for instance like so:
<class>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
<type>
<input>Text</input>
<input>Text</input>
</type>
</class>
What you could do is:
$xml = simplexml_load_file("filepath");
$classes = $xml->$class;
foreach ($classes as $keyClass => $class) {
echo "<ul><li>Class</li><ul>";
$types = $class->type;
foreach ($types as $keyType => $type) {
echo "<li>Type</li><ul>";
$inputs = $type->input;
foreach ($inputs as $keyInput => $input) {
echo "<li>Input</li>";
}
echo "</ul>";
}
echo "</ul></ul>";
}

SOAP request not returning a response

I am making a request to a search directory that looks up HIV specialists. Here is the documentation they provide: http://mobile.aahivm.org/getinfo.asmx?op=GetProviders
I use PHP's cUrl to make the request. Any idea why nothing is being returned?
<?php
$curlData = '<?xml version="1.0" encoding="utf-8"?>
<soap12:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap12="http://www.w3.org/2003/05/soap-envelope">
<soap12:Body>
<GetProviders xmlns="http://localhost">
<fname></fname>
<lname></lname>
<locationzip></locationzip>
<locationcity></locationcity>
<locationstate>New York</locationstate>
<locationcountry></locationcountry>
<primaryservicesid></primaryservicesid>
<credentials></credentials>
<specialty></specialty>
<specialtycare></specialtycare>
<support></support>
<paymentoptions></paymentoptions>
<member></member>
</GetProviders>
</soap12:Body>
</soap12:Envelope>';
$url='http://mobile.aahivm.org/getinfo.asmx?op=GetProviders';
$curl = curl_init();
$length = strlen($curlData);
curl_setopt ($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_VERBOSE, true);
curl_setopt($curl,CURLOPT_HTTPHEADER,array (
'POST /getinfo.asmx HTTP/1.1',
'Host: mobile.aahivm.org',
'Content-Type: application/soap+xml; charset=utf-8',
'Content-Length:'=>$length,
'SOAPAction: "http://localhost/GetProviders"'
));
curl_setopt ($curl, CURLOPT_POST, 1);
curl_setopt ($curl, CURLOPT_POSTFIELDS, $curlData);
//$result = substr(curl_exec($curl), 285, -72); ///remove SOAP envelope!
$result = curl_exec($curl);
print_r("Curl result: ".$result."<br><br><hr>");
curl_close ($curl);
$arr2 = array();
$arr2[] = json_decode($result, true);
////
foreach ($arr2 as $key=>$value) {
//echo $value;
$next[] = $value;
foreach ($next as $key=>$value) {
//echo $value;
$next[] = $value;
foreach ($next as $key=>$value) {
echo $key."=".$value."<br />";
}
echo "--<br /><br />";
}
}
/////
?>
Are you looking to retrieve all of the providers in the response?
In their documentation (http://mobile.aahivm.org/getinfo.asmx?op=GetProviders) it says " The placeholders shown need to be replaced with actual values." So im assuming you will need to send with your request, some sort of values for it to search for.
Hope this helps a bit

Read xml data from url using curl and php

I want to read XML data from a URL. I have the URL as follows:
http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A
Here is my code:
$Url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $Url);
$output = curl_exec($ch);
$resultCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
// Close the cURL resource, and free system resources
curl_close($ch);
Could anyone please tell me how to read xml data?
Here is some sample code (XML parsing module may not be available on your PHP installation):
<?php
$url="http://www.arrowcast.net/fids/mco/fids.asp?sort=city&city=&number=&airline=&adi=A";
$ch = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_URL, $url); // get the url contents
$data = curl_exec($ch); // execute curl request
curl_close($ch);
$xml = simplexml_load_string($data);
print_r($xml);
?>
The variable $xml now is a multi-dimensional key value array and you should easily be able to figure out how to get the elements from there.
// the SAX way:
XMLReader myReader = XMLReaderFactory.createXMLReader();
myReader.setContentHandler(handler);
myReader.parse(new InputSource(new URL(url).openStream()));
// or if you prefer DOM:
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new URL(url).openStream());
This is the demo of how to get channel id from rss feed of youtube in which i read xml data from url using curl.
$channel_id = 'XXXXXXXX'; // put the channel id here
//using curl
$url = 'https://www.youtube.com/feeds/videos.xml?channel_id='.$channel_id.'&orderby=published';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
//curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$response = curl_exec($ch);
curl_close($ch);
$response=simplexml_load_string($response);
$json = json_encode($response);
$youtube= json_decode($json, true);
$count = 0;
if(isset($youtube['entry']['0']) && $youtube['entry']['0']!=array())
{
foreach ($youtube['entry'] as $k => $v) {
$yt_vids[$count]['id'] = str_replace('http://www.youtube.com/watch?v=', '', $v['link']['#attributes']['href']);
$yt_vids[$count]['title'] = $v['title'];
$count++;
}
}
else
{
$yt_vids[$count]['id']=str_replace('http://www.youtube.com/watch?v=', '', $youtube['entry']['link']['#attributes']['href']);
$yt_vids[$count]['title']=$youtube['title'];
}
echo "<pre>";
print_r($yt_vids);

Categories