I need to parse this web page https://www.galliera.it/118 getting the numbers under the coloured bars.
This is my code (that doesn't work!!) ...
<?php
ini_set('display_errors', 1);
$url = 'https://www.galliera.it/118';
print "The url ... ".$url;
echo '<br>';
echo '<br>';
//#Set CURL parameters ...
$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);
curl_setopt($ch, CURLOPT_PROXY, '');
$data = curl_exec($ch);
curl_close($ch);
//print "Data ... ".$data;
//echo '<br>';
//echo '<br>';
$dom = new DOMDocument();
#$dom->loadHTML($data);
$xpath = new DOMXPath($dom);
// This is the xpath for a number under a bar ....
// /html/body/div[2]/div[1]/div/div/ul/li[6]/span
// How may I get it?
// The following code doesn't work, it's only to show my goals ..
$greenWaitingNumber = $xpath->query('/html/body/div[2]/div[1]/div/div/ul/li[6]/span');
$theText = (string).$greenWaitingNumber;
print "Data ... ".$theText;
echo '<br>';
echo '<br>';
?>
Any suggestions / examples / alternatives?
Here is your php script that is mining request by you data in nicely sorted array, you can see the results of script and change the structure as you need it. Cheers!
$html = file_get_contents("https://www.galliera.it/118");
$dom = new DOMDocument();
$dom->loadHTML($html);
$finder = new DOMXPath($dom);
// find all divs class row
$rows = $finder->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' row ')]");
$data = array();
foreach ($rows as $row) {
$groupName = $row->getElementsByTagName('h2')->item(0)->textContent;
$data[$groupName] = array();
// find all div class box
$boxes = $finder->query("./*[contains(concat(' ', normalize-space(#class), ' '), ' box ')]", $row);
foreach ($boxes as $box) {
$subgroupName = $box->getElementsByTagName('h3')->item(0)->textContent;
$data[$groupName][$subgroupName] = array();
$listItems = $box->getElementsByTagName('li');
foreach ($listItems as $k => $li) {
$class = $li->getAttribute('class');
$text = $li->textContent;
if (!strlen(trim($text))) {
// this should be the graph bar so kip it
continue;
}
// I see only integer numbers so I cast to int, otherwise you can change the type or event not cast it
$data[$groupName][$subgroupName][] = array('type' => $class, 'value' => (int) $text);
}
}
}
echo '<pre>' . print_r($data, true) . '</pre>';
and output is something like:
Array
(
[SAN MARTINO - 15:30] => Array
(
[ATTESA: 22] => Array
(
[0] => Array
(
[type] => rosso
[value] => 1
)
[1] => Array
(
[type] => giallo
[value] => 12
)
[2] => Array
(
[type] => verde
[value] => 7
)
[3] => Array
(
[type] => bianco
[value] => 2
)
)
[VISITA: 45] => Array
(
[0] => Array
(
[type] => rosso
[value] => 5
)
...
This might help simplify your xpath statement for this specific instance.
This will find all li elements with a class attribute matching "verde" that has a span element under it.
the // notation means "match at any level in the document" so you don't have to build your query from root
/* #var $node DOMElement */
$greenWaitingNumber = $xpath->query('//li[#class="verde"]/span');
foreach( $greenWaitingNumber as $node )
{
echo $node->nodeValue;
}
*note this will not deal with class="verde foo bar"
If you're only interested in one particular value...
$greenWaitingNumber = $xpath->query('/html/body/div[2]/div[1]/div/div/ul/li[6]/span');
$theText = $greenWaitingNumber[0]->nodeValue;
This will print "2"
Related
i need to convert an xml to array.
I get the xml from an online api.
My code so far:
function download_page($path){
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$path);
curl_setopt($ch, CURLOPT_FAILONERROR,1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_TIMEOUT, 15);
$retValue = curl_exec($ch);
curl_close($ch);
return $retValue;
}
$sXML = download_page('https://url/api/user/distgroup/domain/user?t=ticketofuser');
echo "xml start: ". htmlentities($sXML);
$oXML = new SimpleXMLElement($sXML);
echo "xml: ". $oXML;
foreach($oXML["distributionGroups"] as $key=>$value)
{
$groups[$key]["group"]["id"]=$value["id"];
$groups[$key]["group"]["domain"]=$value["domain"];
$groups[$key]["group"]["name"]=$value["name"];
$groups[$key]["group"]["type"]=$value["type"];
$groups[$key]["group"]["loggedIn"]=$value["loggedIn"];
$groups[$key]["group"]["nightMode"]=$value["nightMode"];
$groups[$key]["group"]["loggedInAgents"]=$value["loggedInAgents"];
$groups[$key]["group"]["freeAgents"]=$value["freeAgents"];
$groups[$key]["group"]["callsWaiting"]=$value["callsWaiting"];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
$_SESSION["groups"]=$groups;
echo "groups: ". $groups;
Afterdownloaded the xml it looks like this when i echo it with htmlentities($sXML);
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<distributionGroups>
<group>
<id>33247</id>
<domain>soluno.se</domain>
<name>Kamoda Support</name>
<type>ATTENDANT</type>
<loggedIn>true</loggedIn>
<nightMode>false</nightMode>
<loggedInAgents>1</loggedInAgents>
<freeAgents>1</freeAgents>
<callsWaiting>0</callsWaiting>
</group>
<group>
<id>33257</id>
<domain>soluno.se</domain>
<name>Test 5</name>
<type>ATTENDANT</type>
<loggedIn>false</loggedIn>
<nightMode>false</nightMode>
<loggedInAgents>0</loggedInAgents>
<freeAgents>0</freeAgents>
<callsWaiting>0</callsWaiting>
</group>
</distributionGroups>
My problem is that my array is empty after my try to foreach fill the array.
What am i doing wrong?
In your second foreach, you are missing the key group. Also, you could use $oXML->group to iterator over the XML elements:
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[]["group"] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row['group']["id"]; // missing 'group' in $row['group']
}
array_multisort($temp, SORT_ASC, $groups);
print_r($temp);
print_r($groups);
Output of $temp:
Array
(
[0] => 33247
[1] => 33257
)
Output of $groups:
Array
(
[0] => Array
(
[group] => Array
(
[id] => 33247
[domain] => soluno.se
[name] => Kamoda Support
[type] => ATTENDANT
[loggedIn] => true
[nightMode] => false
[loggedInAgents] => 1
[freeAgents] => 1
[callsWaiting] => 0
)
)
[1] => Array
(
[group] => Array
(
[id] => 33257
[domain] => soluno.se
[name] => Test 5
[type] => ATTENDANT
[loggedIn] => false
[nightMode] => false
[loggedInAgents] => 0
[freeAgents] => 0
[callsWaiting] => 0
)
)
)
Or you could remove "group" in your first array :
$oXML = new SimpleXMLElement($sXML);
$groups = [] ;
foreach($oXML->group as $group)
{
$groups[] = [
'id' => (string)$group->id,
'domain' => (string) $group->domain,
'name' => (string) $group->name,
'type' => (string) $group->type,
'loggedIn' => (string) $group->loggedIn,
'nightMode' => (string) $group->nightMode,
'loggedInAgents' => (string) $group->loggedInAgents,
'freeAgents' => (string) $group->freeAgents,
'callsWaiting' => (string) $group->callsWaiting,
];
}
$temp=array();
foreach ($groups as $key => $row) {
$temp[$key] = $row["id"];
}
array_multisort($temp, SORT_ASC, $groups);
You could make it more flexible by getting the code to copy across each element within the group, adding an element to the array with the element name. This means that as the XML changes (or if) then the code will still retain all of the data being passed over.
I've also merged the two loops, so that $temp is set in the same loop as the main data.
$oXML = new SimpleXMLElement($sXML);
$groups = array();
$temp=array();
foreach ( $oXML->group as $group ) {
$data = array();
foreach ( $group as $element ) {
$data[ $element->getName() ] = (string)$element;
}
$groups[]["group"] = $data;
$temp[] = $data["id"];
}
print_r($temp);
print_r($groups);
new SimpleXMLElement($sXML) creates an object (not an array) of an XML element. So in your case, this $oXML = new SimpleXMLElement($sXML); gives you the distributionGroups element. From there you can access its child elements like foreach($oXML->group as $group), but remember that $group would also be an instance of SimpleXMLElement(). To access the content of the element you actually need to cast the object, i.e. (int) $group->loggedInAgents, to get an integer value. Otherwise $group-> loggedInAgents will actually give you another SimpleXMLElement() object, rather than a variable.
read more in the docs
Trying to echo a couple of values from the CURL JSON response so i can put them in to a foreach loop but i can only get single indexed values to work.
$request = curl_init($api); // initiate curl object
curl_setopt($request, CURLOPT_HEADER, 0); // set to 0 to eliminate header info from response
curl_setopt($request, CURLOPT_RETURNTRANSFER, 1); // Returns response data instead of TRUE(1)
//curl_setopt($request, CURLOPT_SSL_VERIFYPEER, FALSE); // uncomment if you get no gateway response and are using HTTPS
curl_setopt($request, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($request, CURLOPT_HTTPHEADER, array(
"Content-Type: application/x-www-form-urlencoded"
));
$response = (string)curl_exec($request); // execute curl fetch and store results in $response
curl_close($request); // close curl object
$result = json_decode($response, true); // true turns it into an array
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
echo 'Last Name: ' . $result[0]['last_name'] . '<br />'; // yet i can return the first value
Example Array output
Array
(
[0] => Array
(
[id] => 34761
[first_name] => A
[last_name] => Bailes
[clinic] =>
[phone] => 7409923279
[fax] => 7409926740
[address1] => 507 Mulberry Heights Rd
[address2] =>
[city] => Pomeroy
[subdivision] => OH
[country_code] =>
[postal_code] => 45769-9573
[timezone] => Array
(
[timezone_type] => 3
[timezone] => America/New_York
)
[state] => OH
)
)
I have json decode set to true for array output
$result = json_decode($response, true); // true turns it into an array
but when i try to echo the 'first_name' values it just returns empty.
echo 'First Name: ' . $result['first_name'] . '<br />'; // why doesnt this work
Yet i can return an indexed value
echo 'First Name: ' . $result[0]['first_name'] . '<br />';
What am i doing wrong here?
Your result array is nested 2 deep. $result is an array of arrays. So:
$result[0]['first_name']
or
foreach ($result as $r) {
echo $r['first_name'];
}
Response depend on server answer your request, the following work perfect to extract access token for example, you can try the following steps to test what you have and extract what you need too
After
$response = curl_exec($ch);
curl_close($ch);
I start to show what I get by
Test:
print_r ($response);
Then go to extract (where server response ) header and body to use what available in each of them
list($header, $body) = explode("\r\n\r\n", $response, 2);
Test:
echo $header;
echo $body;
then I’m extract item in $body to use in my code using stdClass
$bodyObject = json_decode($body);
Test:
print_r($bodyObject);
Test:
echo $bodyObject->access_token;
i am having a problem with a function that i have got online from somewhere, the issue is the function is supposed to return a specific value in an array but whenever i echo the function, it gives me a big array in the print_r style! here is the code:-
function USPSParcelRate() {
$userName = 'XXXXXXXXXXX';
$orig_zip = '10459';
//Shipping Request
$dest_zip = getshipinfo('zip_code');
foreach($_SESSION as $name=> $value){
if($value>0){
if(substr($name, 0, 5)=='cart_'){
if(substr($name, 0, 5)=='cart_'){
$id=substr($name, 5, (strlen($name)-5));
$query = mysql_query("SELECT `category`,`subcategory` FROM `items` WHERE `id`='".mysql_real_escape_string((int)$id)."' ");
while($query_row = mysql_fetch_assoc($query)){
$category = $query_row['category'];
$subcategory = $query_row['subcategory'];
}
$sql = mysql_query("SELECT `pounds`,`ounces` FROM `categories` WHERE `category`='".$category."' AND `subcategory`='".$subcategory."' ");
while($sql_row = mysql_fetch_assoc($sql)){
$pounds = $sql_row['pounds'];
$ounces = $sql_row['ounces'];
}
}
}
}
}
$url = "http://production.shippingapis.com/shippingapi.dll";
$ch = curl_init();
// set the target url
curl_setopt($ch, CURLOPT_URL,$url);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
// parameters to post
curl_setopt($ch, CURLOPT_POST, 1);
$data = "API=RateV4&XML=http://production.shippingapis.com/shippingapi.dll=<RateV4Request USERID='151ALHAD4911' >
<Revision/>
<Package ID='1ST'>
<Service>PRIORITY</Service>
<ZipOrigination>$orig_zip</ZipOrigination>
<ZipDestination>$dest_zip</ZipDestination>
<Pounds>$pounds</Pounds>
<Ounces>$ounces</Ounces>
<Container>NONRECTANGULAR</Container>
<Size>LARGE</Size>
<Width>12</Width>
<Length>15.5</Length>
<Height>6</Height>
<Girth>31</Girth>
</Package>
</RateV4Request>";
// send the POST values to USPS
curl_setopt($ch, CURLOPT_POSTFIELDS,$data);
$result=curl_exec ($ch);
$data = strstr($result, '<?');
// echo '<!-- '. $data. ' -->'; // Uncomment to show XML in comments
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $data, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (array_key_exists('attributes',$xml_elem)) {
list($level[$xml_elem['level']],$extra) = array_values($xml_elem['attributes']);
} else {
$level[$xml_elem['level']] = $xml_elem['tag'];
}
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
eval($php_stmt);
}
}
curl_close($ch);
//echo '<pre>'; print_r($params); echo'</pre>'; // Uncomment to see xml tags
return $params['RateV4Response']['1ST']['1']['RATE'];
}
echo USPSParcelRate();
this code doesn't give me any results unless i uncomment the print_r lines and it shows it like this:-
Array
(
[RATEV4RESPONSE] => Array
(
[1ST] => Array
(
[ZIPORIGINATION] => XXXXX
[ZIPDESTINATION] => XXXXX
[POUNDS] => 3
[OUNCES] => 5
[CONTAINER] => NONRECTANGULAR
[SIZE] => LARGE
[WIDTH] => 12
[LENGTH] => 16
[HEIGHT] => 6
[GIRTH] => 31
[ZONE] => 5
[1] => Array
(
[MAILSERVICE] => Priority Mail 3-Day<sup>™</sup>
[RATE] => 14.05
)
)
)
)
how can i echo the value of this line only :-
[RATE] => 14.05
Array keys are case sensitive, so...
return $params['RATEV4RESPONSE']['1ST'][1]['RATE'];
Should do it
Myself and a few friends are trying to use WHMCS to offer services in a virtual world. Issue is WHMCS does not provide a simple way to search for a specific client record without already having the client id, which wouldn't be stored anywhere besides the WHMCS database. the api function getclients returns results in an XML format, issue is when you search for a client using this method you can only search for firstname, lastname, or email address. Now we have tried passing the variables for firstname and lastname(they have to be passed separately) This unfortunatly returns the client records for all clients that X firstname OR Y Lastname, instead of narrowing down the one client with both X and Y.
What I want to know is how to search PHP array generated from an XML result to try and grab the client records for only the client we are looking for.
The results are posted as such:
Array ( [WHMCSAPI] => Array ( [ACTION] => getclients [RESULT] => success [TOTALRESULTS] => 2 [STARTNUMBER] => 0 [NUMRETURNED] => 2 [CLIENTS] => Array ( [CLIENT] => Array ( [ID] => 9 [FIRSTNAME] => Test1 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test1#test.com [DATECREATED] => 2013-04-24 [GROUPID] => 1 [STATUS] => Active ) [CLIENT1] => Array ( [ID] => 20 [FIRSTNAME] => Test3 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test#test.com [DATECREATED] => 2014-01-20 [GROUPID] => 0 [STATUS] => Active ) ) ) )
The code we try using to search is:
$postfields["action"] = "getclients";
$postfields["search"] = $firstname;
$postfields["search"] = $lastname;
$postfields["responsetype"] = "xml";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$xml = curl_exec($ch);
if (curl_error($ch) || !$xml) $xml = '<whmcsapi><result>error</result>'.
'<message>Connection Error</message><curlerror>'.
curl_errno($ch).' - '.curl_error($ch).'</curlerror></whmcsapi>';
curl_close($ch);
$arr = whmcsapi_xml_parser($xml); # Parse XML
$client = searchClient($firstname, $lastname, $arr);
print_r($client); # Output XML Response as Array
/*
Debug Output - Uncomment if needed to troubleshoot problems
echo "<textarea rows=50 cols=100>Request: ".print_r($postfields,true);
echo "\nResponse: ".htmlentities($xml)."\n\nArray: ".print_r($arr,true);
echo "</textarea>";
*/
function whmcsapi_xml_parser($rawxml) {
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $rawxml, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
$alreadyused = array();
$x=0;
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (in_array($xml_elem['tag'],$alreadyused)) {
$x++;
$xml_elem['tag'] = $xml_elem['tag'].$x;
}
$level[$xml_elem['level']] = $xml_elem['tag'];
$alreadyused[] = $xml_elem['tag'];
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
#eval($php_stmt);
}
}
return($params);
}
function searchClient($first, $last, $array)
{
foreach ($array as $key => $val)
{
if($val['FIRSTNAME'] == $first && $val['LASTNAME'] == $last)
{
return $key;
}
}
return null;
}
?>
This returns a blank result. I will admit I am not entirely sure how to do this so any pointers will help.
You are able to "search for a specific client record" via email address utilizing their api and they now support json format for responsetype
"Please note either the clientid or email is required."
http://docs.whmcs.com/API:Get_Clients_Details
I need to output an array with a specif format from a cURL request. I tried many ways to format the XML result as needed without luck.
Here's the PHP code
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
print_r($response);
?>
It prints the following XML
<servicos>
<cservico>
<codigo>41106</codigo>
<valor>16,90</valor>
<prazoentrega>3</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
<cservico>
<codigo>40045</codigo>
<valor>19,20</valor>
<prazoentrega>1</prazoentrega>
...
<erro>0</erro>
<msgerro>
</msgerro>
</cservico>
</servicos>
Or the following array if I apply $xml = new SimpleXMLElement($response);
SimpleXMLElement Object
(
[cServico] => Array
(
[0] => SimpleXMLElement Object
(
[Codigo] => 41106
[Valor] => 16,90
[PrazoEntrega] => 3
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
[1] => SimpleXMLElement Object
(
[Codigo] => 40045
[Valor] => 19,20
[PrazoEntrega] => 1
...
[Erro] => 0
[MsgErro] => SimpleXMLElement Object
(
)
)
)
)
What I need to return is and Array like this. I tried almost every method found in other questions here but never got a good way to construct this two-dimension array.
array(
'Option Name' => array(
'id'=>'40045',
'quote'=>'20,20',
'days'=>'1',
),
'Option Name' => array(
'id'=>'40215',
'quote'=>'29,27',
'days'=>'3',
)
)
*Option Name will be retrieved afterwards by ID code.
This should work flawlessly!
$xml = simplexml_load_string($response);
$json = json_encode($xml);
$arr = json_decode($json,true);
$temp = array();
foreach($arr as $k=>$v) {
foreach($v as $k1=>$v1) {
$temp[$k][$k1] = $v1;
}
}
echo "<pre>";print_r($temp);echo "</pre>";
http://ka.lpe.sh/2012/07/26/php-convert-xml-to-json-to-array-in-an-easy-way/
Try this function (pass the response to it and it should return you your array) :
function getArrayFromResponse($response) {
$xml = new SimpleXMLElement($response);
$array = array();
foreach($xml->cServico as $node){
$array[] = array(
'id' => $node->Codigo,
'quote' => $node->Valor,
'days' => $node->PrazoEntrega
);
}
return $array;
}
$ch = curl_init();
$sendurl = "http://example.com";
curl_setopt($ch, CURLOPT_URL, $sendurl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($ch);
curl_close($ch);
$response = preg_replace("/(<\/?)(\w+):([^>]*>)/", "$1$2$3", $data);
$xml = new \SimpleXMLElement($response);
$array = json_decode(json_encode((array)$xml), TRUE);
echo "<pre>";
print_r($array);
Working charming for me.
I finally got it. After testing all your suggestions and many others found on google, I came up with this:
<?php
$request_url = "http://ws.correios.com.br/calculador/CalcPrecoPrazo.aspx?nCdEmpresa=&sDsSenha=&sCepOrigem=71939360&sCepDestino=72151613&nVlPeso=1&nCdFormato=1&nVlComprimento=16&nVlAltura=5&nVlLargura=15&sCdMaoPropria=s&nVlValorDeclarado=200&sCdAvisoRecebimento=n&nCdServico=41106%2C40045&nVlDiametro=0&StrRetorno=xml 4110616,9034,000,001,50SN04004519,2014,000,002,00SS0";
//Setup cURL Request
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $request_url);
curl_setopt($curl, CURLOPT_TIMEOUT, 130);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$response = curl_exec($curl);
curl_close($curl);
$xml = simplexml_load_string($response);
$services = $xml->cServico;
$result = array();
foreach($services as $service) {
$id = $service->Codigo->__toString();
$quote = $service->Valor->__toString();
$delivery_days = $service->PrazoEntrega->__toString();
//Get simplified service name (option_name)
switch ($id) {
case "40010":
case "40096":
case "40436":
case "40444":
case "40568":
case "40606":
$option_name = 'SEDEX'; break;
case "81019":
case "81868":
case "81833":
case "81850":
$option_name = 'e-SEDEX'; break;
case "41106":
case "41068":
$option_name = 'PAC'; break;
case "40045":
case "40126":
$option_name = 'SEDEX a Cobrar'; break;
case "40215":
$option_name = 'SEDEX 10'; break;
case "40290":
$option_name = 'SEDEX Hoje'; break;
case "81027":
$option_name = 'e-SEDEX Prioritário'; break;
case "81035":
$option_name = 'e-SEDEX Express'; break;
}
$result[$option_name] = array('id' => $id, 'quote' => $quote, 'delivery_days' => $delivery_days);
}
?>
The final secret was to add __toString() to convert values returned as array to a simple string. It prints perfectly. Thank you guys!!
Array
(
[PAC] => Array
(
[id] => 41106
[quote] => 16,90
[delivery_days] => 3
)
[SEDEX a Cobrar] => Array
(
[id] => 40045
[quote] => 19,20
[delivery_days] => 1
)
)