I'd appreciate if someone could help me to solve this issue.
I'm getting this XML by reading a XML file through de code:
$x = simplexml_load_file($link);
$g = $x->attributeGroup;
foreach($g->xpath("//PARAMETER") as $attr){
var_dump((string)$attr->attributes()->ID);
var_dump((string)$attr->attributes()->VALUE);
var_dump((string)$attr); // for text value
}
I need to get the VALUE inside ID=sitPag, but I'm not able to.
Could anybody help me to do that?
<consulta>
<PARAMETER>
<PARAM ID="CodEmp" VALUE="1234"/>
<PARAM ID="Pedido" VALUE="00010714"/>
<PARAM ID="Valor" VALUE="351,20"/>
<PARAM ID="tipPag" VALUE="02"/>
<PARAM ID="sitPag" VALUE="00"/>
<PARAM ID="ValorPago" VALUE="000000351,20"/>
<PARAM ID="dtPag" VALUE="15012020"/>
<PARAM ID="codAut" VALUE=""/>
<PARAM ID="numId" VALUE=""/>
<PARAM ID="compVend" VALUE=""/>
<PARAM ID="tipCart" VALUE=""/>
</PARAMETER>
</consulta>
After calling simplexml_load_file(), I'm gettin it:
object(SimpleXMLElement)#3 (1) { ["PARAMETER"]=> object(SimpleXMLElement)#5 (1) { ["PARAM"]=> array(11) { [0]=> object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(6) "CodEmp" ["VALUE"]=> string(26) "1234" } } [1]=> object(SimpleXMLElement)#7 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(6) "Pedido" ["VALUE"]=> string(8) "00010714" } } [2]=> object(SimpleXMLElement)#8 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(5) "Valor" ["VALUE"]=> string(6) "351,20" } } [3]=> object(SimpleXMLElement)#9 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(6) "tipPag" ["VALUE"]=> string(2) "02" } } [4]=> object(SimpleXMLElement)#10 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(6) "sitPag" ["VALUE"]=> string(2) "00" } } [5]=> object(SimpleXMLElement)#11 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(9) "ValorPago" ["VALUE"]=> string(12) "000000351,20" } } [6]=> object(SimpleXMLElement)#12 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(5) "dtPag" ["VALUE"]=> string(8) "15012020" } } [7]=> object(SimpleXMLElement)#13 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(6) "codAut" ["VALUE"]=> string(0) "" } } [8]=> object(SimpleXMLElement)#14 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(5) "numId" ["VALUE"]=> string(0) "" } } [9]=> object(SimpleXMLElement)#15 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(8) "compVend" ["VALUE"]=> string(0) "" } } [10]=> object(SimpleXMLElement)#16 (1) { ["#attributes"]=> array(2) { ["ID"]=> string(7) "tipCart" ["VALUE"]=> string(0) "" } } } } }
It might not be the most efficient (you have to go through each PARAM element until the desired one is found, which could be many), but this will get the job done.
$x = simplexml_load_string($xmlString);
foreach($x->PARAMETER->PARAM as $param){
if((string)$param->attributes()->ID == "sitPag")
{
echo (string)$param->attributes()->VALUE;
break;
}
}
DEMO
Use Xpath expression to fetch the nodes or values. SimpleXMLElement::xpath() returns an array of SimpleXMLElement instances.
$consulta = new SimpleXMLElement($xml);
$params = $consulta->xpath('PARAMETER/PARAM[#ID="sitPag"]');
$sitPag = isset($params[0]) ? (string)$params[0]['VALUE'] : '';
var_dump($sitPag);
In DOM you can use DOMXpath::evaluate() to fetch the attribute value directly:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$sitPag = $xpath->evaluate('string(/consulta/PARAMETER/PARAM[#ID="sitPag"]/#VALUE)');
var_dump($sitPag);
In DOM you can use DOMXpath::evaluate() to fetch the attribute value directly:
$document = new DOMDocument();
$document->loadXML($xml);
$xpath = new DOMXpath($document);
$sitPag = $xpath->evaluate('string(/consulta/PARAMETER/PARAM[#ID="sitPag"]/#VALUE)');
var_dump($sitPag);
Or
$x = simplexml_load_string($xmlString);
foreach($x->PARAMETER->PARAM as $param){
if((string)$param->attributes()->ID == "sitPag")
{
echo (string)$param->attributes()->VALUE;
break;
}
}
Related
Im trying many days now to select data from this db
[1]: https://i.stack.imgur.com/QA34L.jpg
I want to print for example all comments
echo $comment['username']." | "; \ Alex | Alex
My php code so far:
[![$m= new MongoDB\Client ("mongodb://127.0.0.1/");
$db = $m->stores;
$collection = $db->storeinfo;][1]][1]
$storez = $collection->find(array("Products.pTHUMBNAIL" => $pThumb));
$o=1;
$afm=array();
foreach ($storez as $stor) {
$afm[$o] = $stor['AFM'];
$record = $collection->findOne(array(
"AFM" => $afm[$o],"Products.pTHUMBNAIL" => $pThumb));
foreach ($record['Products'] as $pro){
if($pThumb == $pro['pTHUMBNAIL']){
echo $temp = $pro['pID']." ";
foreach($pro as $pro1['pCOMMENTS']) {
foreach($pro1 as $com['Comment']) {
var_dump($com['Comment']);
/*
foreach($com as $comment) {
echo $comment['username'];
}
*/
}
}
}
}
$o += 1;
}
It seems that i just cannot find the correct foreach to loop through my Comment array
var_dump output:
099360111/1 object(MongoDB\BSON\ObjectId)#55 (1) { ["oid"]=> string(24) "6003403a695900000c002649" } string(11) "099360111/1" string(9) "Old Skool" string(2) "75" string(4) "Vans" string(25) "Leather and textile upper" string(2) "44" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "7" object(MongoDB\Model\BSONArray)#65 (1) { ["storage":"ArrayObject":private]=> array(1) { [0]=> object(MongoDB\Model\BSONDocument)#10 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#73 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#45 (1) { ["milliseconds"]=> string(13) "1611028053000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } } } 099360666/1 object(MongoDB\BSON\ObjectId)#44 (1) { ["oid"]=> string(24) "6006563a3f1c0000c80034a8" } string(11) "099360666/1" string(12) "old school 2" string(2) "50" string(4) "Vans" string(11) "black/white" string(8) "42,43,43" string(18) "Men/Shoes/Trainers" string(52) "http://127.0.0.1/pricedoc/assets/img/products/p1.jpg" string(1) "6" object(MongoDB\Model\BSONArray)#79 (1) { ["storage":"ArrayObject":private]=> array(2) { [0]=> object(MongoDB\Model\BSONDocument)#7 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#39 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#68 (1) { ["milliseconds"]=> string(13) "1611028089000" } ["text"]=> string(21) "1st comment from user" ["rating"]=> string(1) "4" } } } } [1]=> object(MongoDB\Model\BSONDocument)#78 (1) { ["storage":"ArrayObject":private]=> array(1) { ["Comment"]=> object(MongoDB\Model\BSONDocument)#77 (1) { ["storage":"ArrayObject":private]=> array(4) { ["username"]=> string(4) "Alex" ["date"]=> object(MongoDB\BSON\UTCDateTime)#76 (1) { ["milliseconds"]=> string(13) "1611030745000" } ["text"]=> string(8) "good!!!!" ["rating"]=> string(1) "5" } } } } } }
What about this?
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach ($comments['Comment'] as $comment) {
echo $comment['text'];
}
}
You used foreach() bad: the index should be added to the first parameter, not in the 'as' part.
Also it helps if you use more clear variable names. That doesn't take too much, but makes it more readable and easy to debug.
After echo $temp = $pro['pID']." ";
foreach($pro['pCOMMENTS'] as $comments) {
foreach($comments as $comment) {
echo $comment['text'];
}
}
array(2) { [0]=> array(2) { ["name"]=> string(16) "Daerah Pertanian" ["sub"]=> array(6) { [0]=> array(2) { ["name"]=> string(5) "Sawah" ["value"]=> string(3) "145" } [1]=> array(2) { ["name"]=> string(18) "Sawah Pasang Surut" ["value"]=> string(3) "455" } [2]=> array(2) { ["name"]=> string(6) "Ladang" ["value"]=> string(3) "678" } [3]=> array(2) { ["name"]=> string(10) "Perkebunan" ["value"]=> string(3) "688" } [4]=> array(2) { ["name"]=> string(19) "Perkebunan Campuran" ["value"]=> string(3) "966" } [5]=> array(2) { ["name"]=> string(16) "Tanaman Campuran" ["value"]=> string(3) "565" } } } [1]=> array(2) { ["name"]=> string(22) "Daerah Bukan Pertanian" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(18) "Hutan Lahan Kering" ["sub"]=> array(2) { [0]=> array(2) { ["name"]=> string(25) "Hutan Lahan Kering Primer" ["value"]=> string(3) "566" } [1]=> array(2) { ["name"]=> string(27) "Hutan Lahan Kering Sekunder" ["value"]=> string(3) "255" } } } [1]=> array(2) { ["name"]=> string(17) "Hutan Lahan Basah" ["sub"]=> array(2) { [0]=> array(1) { ["name"]=> string(24) "Hutan Lahan Basah Primer" } [1]=> array(1) { ["name"]=> string(26) "Hutan Lahan Basah Sekunder" } } } } } }
I have an array like I mention above, so I want to print out every "name" key including the index (number) of it's array parent,
for example when I print out "Tanaman Campuran" so all index parent is (0)(5) and when I print "Hutan Lahan Basah Sekunder" the index parent is (1)(1)(1)
how can I achieve it?
here is some recursive function that I've tried
$GLOBALS['all'] = '';
function printout($arr){
foreach ($arr as $ia=>$a){
if(is_array($a)){
foreach ($a as $ib=>$b){
if(is_array($b)){
printout($b);
}
else{
if ($ib == 'name') {
$GLOBALS['all'] .= $ia;
echo '<tr>';
echo '<td>' . $b . ' (' . $ia . ')</td>';
echo '</tr>';
$GLOBALS['all'] = '';
}
}
}
}
}
}
*sorry for my bad explanation, I hope you guys can understand it
You could use the following function:
function search(array $array, $name)
{
foreach ($array as $key => $entry) {
if ($entry['name'] === $name) {
return [$key];
}
if (isset($entry['sub']) && $found_keys = search($entry['sub'], $name)) {
return array_merge([$key], $found_keys);
}
}
return null;
}
It returns:
if the value was directly found, an array of one containing the associated index,
if it wasn't but was found in any descendant item, an array merging its index with the indices of said descendant,
null if it wasn't found in that part of the tree.
Note: if a given name is present several times, it will only find the first occurrence.
Demo: https://3v4l.org/1hGr1
I have written below lines of code
public function shiftarray($cursor, $arg)
{
$keyarguments = array("first_name","roll_no");
$arrayStudents =array();
foreach ($cursor as $k => $row)
{
foreach ($keyarguments as $key)
{
if (strcasecmp($row[$key], $arg) == 0)
{
array_unshift($arrayStudents, $row);
}
else
{
}
}
}
return $arrayStudents;
}
I have array of students in $cursor like
{ [0]=> array(50) { ["_id"]=> object(MongoId)#23 (1) { ["$id"]=> string(24) "58131c7799fbad4c1d000202" } ["student_id"]=> float(2) ["registration_temp_perm_no"]=> string(1) "1" ["roll_no"]=> float(1) ["admission_date"]=> string(10) "01/07/2016" ["first_name"]=> string(7) "Neil" ["middle_name"]=> string(4) "David" ["last_name"]=> string(6) "Stephan" ["dob"]=> string(10) "12/03/1981" ["gender"]=> string(6) "Female" ["blood_group"]=> string(2) "A+" ["birth_place"]=> string(11) "Sadar Bazar" ["nationality"]=> string(6) "Indian" ["language"]=> string(7) "English" ["religion"]=> string(8) "Agnostic" ["address_line1"]=> string(20) "4148 Hazelcrest Hill" ["address_line2"]=> string(20) "22883 Memorial Place" ["city"]=> string(11) "Sadar Bazar" ["state"]=> string(13) "Uttar Pradesh" ["pincode"]=> string(6) "190010" ["country"]=> string(5) "India" ["phone1"]=> string(10) "9039180419" ["phone2"]=> string(10) "7681559402" ["email"]=> string(24) "educianstudent#gmail.com" ["is_sms_enabled"]=> string(3) "Yes" ["is_active"]=> int(1) ["has_finished"]=> int(0) ["student_category"]=> string(1) "5" ["course"]=> string(24) "58131c7099fbad4c1d0001c2" ["Biometric_ID"]=> string(1) "1" ["siblings"]=> string(14) "Cynthia Taylor" ["guardian_name"]=> string(14) "Cynthia Taylor" ["guardian_occupation"]=> string(13) "Senior Editor" ["guardian_qualification"]=> string(20) "Research Assistant I" ["guardian_email_id"]=> string(23) "educianparent#gmail.com" ["gaurdain_contact_details"]=> string(10) "9419513603" ["guardian_relationship"]=> string(6) "Father" ["height"]=> string(3) "4.9" ["weight"]=> string(4) "34.9" ["allergies"]=> string(0) "" ["batch"]=> int(2) ["academicyear"]=> string(4) "2015" ["batchhistory"]=> array(1) { [0]=> array(5) { ["batchid"]=> float(2) ["academic_year"]=> string(4) "2015" ["course"]=> string(24) "58131c7099fbad4c1d0001c2" ["sequenceno"]=> int(1) ["courseId"]=> object(MongoId)#24 (1) { ["$id"]=> string(24) "58131c7099fbad4c1d0001c2" } } } ["uploads"]=> array(1) { ["profile_pic"]=> string(39) "58131c7799fbad4c1d000202schoolgirl2.jpg" } ["created_at"]=> NULL ["updated_at"]=> string(0) "" ["routearray"]=> array(2) { [0]=> array(5) { ["routeid"]=> int(2) ["academicyear"]=> string(4) "2016" ["current"]=> int(0) ["vehicleno"]=> string(9) "JK01S8764" ["dateofassignment"]=> string(10) "09/28/2016" } [1]=> array(5) { ["routeid"]=> int(3) ["academicyear"]=> string(4) "2016" ["current"]=> int(1) ["vehicleno"]=> string(9) "JK01S8764" ["dateofassignment"]=> string(10) "11/17/2016" } } ["HostelAlloted"]=> array(7) { ["Food Preferences"]=> string(4) "Both" ["Hostel"]=> object(MongoId)#25 (1) { ["$id"]=> string(24) "58138aee99fbade41e000031" } ["Floor"]=> string(7) "Floor_1" ["RoomNumber"]=> int(11) ["Approved"]=> string(3) "yes" ["Approved On"]=> object(MongoDate)#26 (2) { ["sec"]=> int(1472322600) ["usec"]=> int(0) } ["Academic Year"]=> string(4) "2016" } ["HostelAllotmentHistory"]=> array(1) { [0]=> array(7) { ["Food Preferences"]=> string(4) "Both" ["Hostel"]=> object(MongoId)#27 (1) { ["$id"]=> string(24) "58138aee99fbade41e000031" } ["Floor"]=> string(7) "Floor_1" ["RoomNumber"]=> int(11) ["Approved"]=> string(3) "yes" ["Approved On"]=> object(MongoDate)#28 (2) { ["sec"]=> int(1472322600) ["usec"]=> int(0) } ["Academic Year"]=> string(4) "2016" } } ["courseId"]=> object(MongoId)#29 (1) { ["$id"]=> string(24) "58131c7099fbad4c1d0001c2" } }
...
...
I am trying to bring those student on the beginning of array whose first name is brian and rest of students should at the bottom.
Now the above code place the students on the top of the array but the rest of the students are ommited/removed. I don't want them to be removed.
I am trying to tweak what code to write in else condition.
Please help!!!
Fill $arrayStudents before the loop otherwise only matches will be collected and unshifted.
Extend example of php.net/unshift
$add = array('big');
$queue = array(
array("orange"),
array("banana"),
array("apple1"),
array("raspberry")
);
array_unshift($queue, $add);
print_r($queue);
In your case: search for keys you want to unshift, the rest goes to the standard $list = array(/list of studends/):
$list = array();
$bringToTop = array('brian', 'elvis');
foreach($data as $item) {
if (/* in in the list to bring on top*/) {
$memory[] = $item;
} else {
$list[] = $item;
}
}
foreach($memory as $item) {
array_unshift($list, $item);
}
print_r($list);
Kind regards
Add $arrayStudents[] = $row; to your else scope. Here is a simple demo to illustrate it.
When matches add the element to the result from the start of array, unmatches add them from the end of the array.
I am working with an xml file that I am trying to parse into json format and then decode to an array. I accomplished this mainly using the built in simplexml_load_string and then json_encode. The issue is when calling simplexml_load_string the xml isn’t fully preserved. It seems like the child nodes for video show as object(stdClass). How could I get all values of the xml file? Link to XML
Code:
$xml = simplexml_load_string( file_get_contents('http://foxsoccer2go.mobilefeeds.performgroup.com/fox/api/videos.xml/channel/home') );
$json = json_encode($xml);
Result:
["results"]=>
object(stdClass)#183 (4) {
["previousPage"]=>
object(stdClass)#184 (1) {
["#attributes"]=>
object(stdClass)#185 (1) {
["exists"]=>
string(5) "false"
}
}
["nextPage"]=>
string(1) "2"
["total"]=>
string(2) "40"
["resultList"]=>
object(stdClass)#186 (1) {
["video"]=>
array(20) {
[0]=>
object(stdClass)#187 (7) {
["#attributes"]=>
object(stdClass)#188 (2) {
["id"]=>
string(7) "2329124"
["type"]=>
string(3) "960"
}
["description"]=>
object(stdClass)#189 (0) {
}
["created"]=>
string(25) "2015-02-18 04:04:52 +0000"
["duration"]=>
string(2) "86"
["images"]=>
object(stdClass)#190 (2) {
["image"]=>
object(stdClass)#191 (1) {
["#attributes"]=>
object(stdClass)#192 (3) {
["id"]=>
string(8) "13503818"
["width"]=>
string(3) "100"
["height"]=>
string(3) "100"
}
}
["thumbnail"]=>
object(stdClass)#193 (1) {
["#attributes"]=>
object(stdClass)#194 (3) {
["id"]=>
string(8) "13503819"
["width"]=>
string(3) "372"
["height"]=>
string(3) "210"
}
}
}
["videoFiles"]=>
object(stdClass)#195 (1) {
["file"]=>
object(stdClass)#196 (1) {
["#attributes"]=>
object(stdClass)#197 (3) {
["id"]=>
string(8) "14704560"
["formatId"]=>
string(3) "400"
["uploaded"]=>
string(4) "true"
}
}
}
["categories"]=>
object(stdClass)#198 (1) {
["category"]=>
string(21) "UEFA Champions League"
}
}
I would suggest just try to parse those values using SimpleXML alone and stick with it. Just access those properties properly. As for those nodes which have been wrapped with character data in it, cast them as (string).
$xml = simplexml_load_string( file_get_contents('http://foxsoccer2go.mobilefeeds.performgroup.com/fox/api/videos.xml/channel/home'));
foreach($xml->results->resultList->video as $video) {
$description = (string) $video->description;
$created = $video->created;
$duration = $video->duration;
$image = $video->images->image;
$thumbnail = (string) $video->images->image;
$video_file = (string) $video->videoFiles->file;
$categories = (string) $video->categories->category;
echo "
Description: $description <br/>
Created: $created <br/>
Duration: $duration <br/>
Categories: $categories <br/>
<hr/>
";
}
Sample Output
I have the following data that I parsed from an xml file and now I have a problem returning the data. How do i return the photo src data from the array within the photo array. Any ideas as to what I am doing wrong?
Code
$xml = simplexml_load_file($url);
$photo_url = $xml['photo']->src;
for ($i=0, $n=count($photo_url); $i<$n; ++$i) {
echo $photo_url[$i].'<br>';
}
Data
["photo"]=>
array(46) {
[0]=>
object(SimpleXMLElement)#2 (1) {
["#attributes"]=>
array(6) {
["id"]=>
string(5) "26001"
["src"]=>
string(36) "1006416.jpg"
["thumb"]=>
string(42) "1006416_thumb.jpg"
["title"]=>
string(16) "album"
["subtitle"]=>
string(6) "01.jpg"
["favorite"]=>
string(0) ""
}
}
[1]=>
object(SimpleXMLElement)#3 (1) {
["#attributes"]=>
array(6) {
["id"]=>
string(5) "26001"
["src"]=>
string(36) "1006417.jpg"
["thumb"]=>
string(42) "1006417_thumb.jpg"
["title"]=>
string(16) "album"
["subtitle"]=>
string(6) "02.jpg"
["favorite"]=>
string(0) ""
}
}
You should use the SimpleXMLElement attributes method, like so:
$xml = simplexml_load_file($url);
foreach( $xml as $xml_node)
{
$attributes = $xml_node->attributes();
echo 'Photo source: ' . $attributes['src'] . "\n";
}
Demo