I can't manage to sort an array alfabetically.
It's an array with cities that I get from an external XML.
The XML looks like this, and it's the node localidad I am trying to sort.
<parada>
<id>506</id>
<localidad>
<![CDATA[ Alvor ]]>
</localidad>
<parada>
<![CDATA[ Alvor Baia Hotel (Bus Stop Alvor Férias) ]]>
</parada>
<lat>37.1296</lat>
<lng>-8.58058</lng>
<horasalida>05:40</horasalida>
</parada>
The relevant code:
$xml = new SimpleXMLElement($viajes);
foreach ($xml->parada as $excursion) {
$newParadasarray[] = $excursion->localidad;
}
$newParadasarray = array_unique($newParadasarray);
foreach ($newParadasarray as $parada) {
if (strpos($parada, 'Almuñecar') !== false)
echo '<option value="Almuñecar">Almuñecar</option>';
if (strpos($parada, 'Benalmádena') !== false)
echo '<option value="Benalmádena Costa">Benalmádena Costa</option>';
if (strpos($parada, 'Estepona') !== false)
echo '<option value="Estepona">Estepona</option>';
etc.
}
I have tried with sort() and array_values().
This is the output of print_r($newParadasarray):
Array (
[0] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[1] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[2] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[4] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[9] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[14] => SimpleXMLElement Object ( [0] => SimpleXMLElement Object ( ) )
[20] => etc.
The problem is that your assigning a SimpleXMLElement into the array, instead you want the content of the element, so just change the line...
$newParadasarray[] = $excursion->localidad;
to
$newParadasarray[] = trim((string)$excursion->localidad);
The cast (string) takes the text content and trim() removes the extra whitespace around it.
I am assuming that you have multiple <parada> elements, so that $xml->parada is returning the correct data.
If you're familiar with DOMDocument you could simply do this:
$doc = new DOMDocument();
$doc->loadXML($xml);
$array = array();
foreach($doc->getElementsByTagName("localidad") as $localidad) {
$array[] = trim($localidad->nodeValue);
}
$array = array_unique($array);
sort($array);
Related
Given a deep array, how do you display line-delimited values from it?
Array (
[0] => Array (
[godzina] => SimpleXMLElement Object (
[0] => 17:00:00
)
[data] => SimpleXMLElement Object (
[0] => 2015-09-02
)
[kurs] => SimpleXMLElement Object (
[0] => 2.03
)
)
)
This is the output I'm expecting:
hours: 17:00:00
date: 2015-09-02
exchange: 2.03
I get this array from an xml, via curl, so the source can't be altered.
Figured Out:
$h = 'godzina';
$hvalue = $zmt[$h];
$d = 'data';
$dvalue = $zmt[$d];
$e = 'kurs';
$evalue = $zmt[$e];
and then echo with [0].
BUT thanks. For foreach loop.
Assuming your array is in a variable $myArr, you should be able to do a simple foreach:
foreach ($myArr[0] as $k => $v) {
echo $k.": ".$v[0]."\n"
}
I am trying to get elements out of a simpleXML array and for some reason I am unable to call them.
Here is the array.
Array
(
[0] => SimpleXMLElement Object
(
[NameChangeIndicator] => N
[NameChangeDate] => SimpleXMLElement Object
(
)
[PreviousName] => SimpleXMLElement Object
(
)
[Score] => 53
[NumberOfSubs] => SimpleXMLElement Object
(
)
[NumberOfJU] => SimpleXMLElement Object
(
)
[DateLastJU] => SimpleXMLElement Object
(
)
[NumberActPrincipals] => 1
[NumberActPrincipalsJU] => SimpleXMLElement Object
(
)
[LastestBankCode] => SimpleXMLElement Object
(
)
[LastestBankCodeDate] => SimpleXMLElement Object
(
)
[NumberRDs] => SimpleXMLElement Object
(
)
[LiqIndicator] => SimpleXMLElement Object
(
)
[TotEnqLast12Mth] => SimpleXMLElement Object
(
)
[TotEnqLast3Mth] => SimpleXMLElement Object
(
)
[RefsNoOfReferences] => SimpleXMLElement Object
(
)
[RefsHighMthPurchases] => SimpleXMLElement Object
(
)
[RefsHighMthPurchasesTermGiven] => SimpleXMLElement Object
(
)
[RefsHighMthPurchasesTermTaken] => SimpleXMLElement Object
(
)
[RefsLowMthPurchases] => SimpleXMLElement Object
(
)
[RefsLowMthPurchasesTermGiven] => SimpleXMLElement Object
(
)
[RefsLowMthPurchasesTermTaken] => SimpleXMLElement Object
(
)
[KissNoOfSuppliers] => SimpleXMLElement Object
(
)
[KissNoOfODSuppliers] => SimpleXMLElement Object
(
)
[KissAmountOS] => SimpleXMLElement Object
(
)
[KissAmountOD] => SimpleXMLElement Object
(
)
[KissPercntage] => SimpleXMLElement Object
(
)
[LatestBankCodeDesc] => SimpleXMLElement Object
(
)
[HoldingCmpName] => SimpleXMLElement Object
(
)
)
)
So I am doing the following call to get the array.
$new_str = htmlspecialchars_decode($str);
$new_str = str_replace('<?xml version="1.0" encoding="UTF-8"?>','',$new_str);
$xml = simplexml_load_string($new_str);
$dom = new SimpleXMLElement($new_str);
$xml_array = $dom->xpath("//*[name()='ReportSummary']");
echo "{$xml_array[0]['Score']}";
But I am unable to pull the object out of the Array. I am not sure if the array
is being correctly sent back to me due to the fact that if I don't decode the string I don't get a array back. The weird thing is that in the array I keep on seeing "SimpleXMLElement Object" and I am not sure if that is correct.
Any help will be appreciated.
As the dump output says, SimpleXML is a type of object, not a way of creating arrays.
These two lines are different ways of writing the same thing, you only need one of them; in either case you end up with a SimpleXMLElement object:
$xml = simplexml_load_string($new_str);
$xml = new SimpleXMLElement($new_str);
The outer array you are seeing is to hold the results of the XPath query, since they can come from anywhere in the XML tree. It is an array of SimpleXMLElement objects.
For how to access data using SimpleXML, see the basic usage page in the PHP manual.
In your case, Score is an element of the document, so needs to be accessed with the $node->property syntax.
Here's a tidied up version of your code:
$new_str = htmlspecialchars_decode($str);
// Are you sure the next line is necessary? That looks like a valid XML opening to me.
$new_str = str_replace('<?xml version="1.0" encoding="UTF-8"?>','',$new_str);
$xml = simplexml_load_string($new_str);
// I think this simpler XPath expression means the same as yours, but I might be wrong
$xpath_results = $xml->xpath('//ReportSummary');
// Beware that the XPath could return no matches, in which case the following
// would give an error. Best to check count($xpath_results) > 0 first.
echo $xpath_results[0]->Score;
To IMSoP: thanks for the help but I had to modify it a bit:
$dom = new SimpleXMLElement($new_str);
$xml_array = $dom->xpath("//*[name()='ReportSummary']");
echo $xml_array[0]->Score;
And from that I got the correct result, thanks a lot!
I would like to get methods from REST XML file via PHP.
I have local REST file, which is in this format:
SimpleXMLElement Object
(
[doc] => SimpleXMLElement Object
(
)
[resources] => SimpleXMLElement Object
(
[#attributes] => Array
(
[base] => https://**url**
)
[resource] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[path] => xml/{accesskey}/project
)
[param] => SimpleXMLElement Object
(
[#attributes] => Array
(
[name] => accesskey
[style] => template
[type] => xs:string
)
)
[method] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => getAllProjects
[name] => GET
)
[response] => SimpleXMLElement Object
(
[representation] => SimpleXMLElement Object
(
[#attributes] => Array
(
[mediaType] => application/xml; charset=utf-8
)
)
)
)
... and so on
I have the following code, but it returns just the first method name:
$file="application.wadl";
$xml = simplexml_load_file($file);
foreach($xml->resources[0]->resource->method->attributes() as $a => $b) {
echo $b,"\n";
}
I would like to extract all of them, not just the first one. How to do that?
Rather than looping over the attributes of one element, you need to loop over all the elements with the same name. Due to the magic of SimpleXML, this is as simple as this:
foreach($xml->resources->resource->method as $method) {
echo $method['id'],"\n";
}
When followed immediately by another operator, as with ->resources, SimpleXML assumes you just want the first element with that name. But if you loop over, it will give you each of them, as a SimpleXML object.
EDIT : It looks like the nesting of your XML means you need some form of recursion (you need to look at $xml->resources->resource->resource->resource->method etc).
Something like this perhaps (untested example)?
function get_methods($base_url, $node)
{
$all_methods = array();
// Child resources: build up the path, and recursively fetch all methods
foreach ( $node->resource as $child_resource )
{
$child_url = $base_url . '/' . (string)$child_resource['path'];
$all_methods = array_merge(
$all_methods,
get_methods($child_url, $child_resource)
);
}
// Methods in this resource: add to array directly
foreach ( $node->method as $method )
{
$method_url = $base_url . '/' .(string)$method['id'];
$all_methods[$method_url] = (string)$method['id'];
}
return $all_methods;
}
print_r( get_methods('/', $xml->resources) );
Incidentally, print_r won't always give you the best view of a SimpleXML object, because they are actually wrappers around non-PHP code. Try this simplexml_dump() function instead.
How to get Cxyabc, Cxy123 and Cxy234 inside an array from below object?
$xml_element = simplexml_load_string($xml,null, LIBXML_NOCDATA);
$childId = $xml_element->Parent->ChildID;
print_r(childId);
SimpleXMLElement Object (
[#attributes] => Array (
[entity] => result
[order-value] => 1
)
[0] => Cxyabc
[1] => Cxy123
[2] => Cxy234
)
Thanks for answers, i tried below one and working fine. string conversion is necessary.
$test = array();
foreach($childId as $value){
$strValue = (string)$value;
array_push($test,$strValue);
}
Try:
$cxyabc = $obj->{0};
$cxy123 = $obj->{1};
The usage of { } is necessary because object properties cannot begin with a digit so $obj->0 is not valid.
You would access the attributes using array notation:
$entity = $obj['entity'];
I just want to get the value from xml node.So I following the code from php document:
SimpleXMLElement::xpath() .But it didn't.And I thought the Xpath is much more inconvenience ,is there a much better way to get the node I want??!
my php code:
<?php
/**
* #author kevien
* #copyright 2010
*/
$arr = array ();
$xml = simplexml_load_file("users.xml");
$result = $xml->xpath('/users/user[#id="126"]/watchHistory/whMonthRecords[#month="2010-09"]/whDateList/date');
while(list( , $node) = each($result)) {
array_push($arr, $node);
}
print_r($arr);
?>
it returns:
Array ( [0] => SimpleXMLElement Object ( [0] => 02 ) [1] => SimpleXMLElement Object ( [0] => 03 ) [2] => SimpleXMLElement Object ( [0] => 06 ) [3] => SimpleXMLElement Object ( [0] => 10 ) [4] => SimpleXMLElement Object ( [0] => 21 ) )
my part of users.xml :
<users>
<user id="126">
<name>老黄牛三</name>
<watchHistory>
<whMonthRecords month="2010-09">
<whDateList month="2010-09">
<date>02</date>
<date>03</date>
<date>06</date>
<date>10</date>
<date>21</date>
</whDateList>
</<whMonthRecords>
</<watchHistory>>
</user>
</users>
Thank you very much!!
Replace your whole loop with:
foreach ($result as $node) {
$arr[] = (string)$node;
}
or even:
$result = array_map('strval', $result);