Getting Value from Object with Characters in Element Name - php

I have an object being passed into a function which I have no control over and it is in the below format, with the root being 'entity'.
object(SimpleXMLElement)#6 (1) { ["#attributes"]=> array(2) { ["id"]=> string(2) "12" ["name"]=> string(17) "Test Object Value" } }
Now I'm trying to pull out just the name by using both the below snippets but both output empty values.
entity[0]->name;
and
entity->{'#attributes'}->name;
Is there a special way to deal with characters in element names when the curly brackets format doesn't work?

You need to use attribute() function for getting the attributes in a simpleXML object. Your code should be something like:
$parsed = $simplexmlObject->entity->attribute()->desiredProperty;
Update: Got this technique from a question asked from me, How to parse value `#attribute` from a SimpleXMLObject in PHP

You can get the name attribute as follows:
$name = $entity->attributes()->name;
echo $name;

Related

PHP: how can I access JSON object

I'm sending this JSON:
[{"tipo":""},{"activo":""},{"titulo":"Servicoasd B"},{"texto":"asdasdasd"}]
to a php file via post method.
There, i do
$obj = json_decode($_POST['sentJson']);
However, I seem to be unable to access the elements of the JSON.
var_dump(($obj));
Shows the object:
array(4) {
[0]=>
object(stdClass)#2 (1) {
["tipo"]=>
string(0) ""
}
[1]=>
object(stdClass)#3 (1) {
["activo"]=>
string(0) ""
}
[2]=>
object(stdClass)#4 (1) {
["titulo"]=>
string(9) "Servico B"
}
[3]=>
object(stdClass)#5 (1) {
["texto"]=>
string(6) "asdasd"
}
}
But if I try
$obj['texto'];
$obj->{'texto'};
$obj[0]['texto'];
$obj[0];
It shows "undefined index texto" or "trying to get property of non object in" and the last one "Object of class stdClass could not be converted to string in". I'm very new to PHP, but still I can't seem to notice what I'm doing wrong. Any help would be appreciated.
Your JSON is a serialized array of four completely different objects, so when you run json_decode, that's what you get: an array.
If you want to access your objects inside that array, access them like you would any other indexed array:
$list = json_decode(...);
foreach($list as $obj) {
var_dump($obj)
}
Or target them explicitly using plain old numerical access.
$list = json_decode(...);
$last = $list[3];
$text = $last->texto;
But really the question you should be asking is why this is the JSON you get. An array with completely different objects at each position is terrible data, and should be fixed.

How do I print Attribute Values of an object(stdClass) in PHP

I'm having a difficult time understanding how to print out an attribute value of an object. The particular example I am working from is this:
object(SimpleXMLElement)#1 (1) {
["links"]=>
object(SimpleXMLElement)#4 (2) {
["#attributes"]=>
array(3) {
["total-matched"]=>
string(2) "31"
["records-returned"]=>
string(2) "10"
["page-number"]=>
string(1) "3"
}
I want to print the value of the links total-matched (which is 31). I've tried this: echo $object->links->total-matched; but I only get the value of 0.
How can I do this?
$object->links->total-matched evaluates as $object->link->total - matched (- is minus, I suppose you should see warning about using unknown constant - turn on error reporting). To access attributes with names like this you can do following: $object->links->{'total-matched'} although in this case, since it's SimpleXML attribute, I think you need to get attributes array:
$attr = $object->links->attributes();
echo $attr['total-matched'];

How can I extract the value from this SimpleXml?

How can I extract the value from this SimpleXml? I keep getting an empty array, and I don't know what I'm doing wrong.
I just want to extract the string "Familial GI Stromal Tumor With Loss of Heterozygosity and Amplification of Mutant KIT.".
object(SimpleXMLElement)#13 (2) {
["#attributes"]=>
array(2) {
["Name"]=>
string(5) "Title"
["Type"]=>
string(6) "String"
}
[0]=>
string(86) "Familial GI Stromal Tumor With Loss of Heterozygosity and Amplification of Mutant KIT."
}
SimpleXMLElement has a __toString() method. For the element you showed in your question, you should be able to just echo the string content.
echo $yourElement;
or if you want it in a variable, you can call __toString() explicitly
$someVar = $yourElement->__toString();
or trigger it by treating the element as a string;
$someVar = "$yourElement";
Just convert it into a string.
var_dump((string) $element);
Anyway, it depends on your xpath.
Thanks for the help, everyone. Turns out I figured it out. I simply had to access it from the array.
$title = $pub->xpath('Item[#Name="Title"]')[0];

PHP Convert array element to string prints "Array"

I query a database to obtain an array of results.
$usersArray = $db->getAllUsers(); // db-Query
If I print out the array's var_dump, its content is structured in form of other arrays:
array(9) { [0]=> **array**(1) { ["column"]=> string(20) "..." } [1]=> **array**(1) { ["column"] (remaining 8 are the same).
Now I need these values (which are correct, so far) to be casted as strings, so that:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
There are several answers to this here and elsewhere, such as
-array_map: here I can actually cast the content as string, but- it prints "Array" instead the value. It tried then getting the content via
$users = array_map('strval',implode( $usersArray));
$users = array_map('strval', print_r($usersArray));
Neither of those worked.
Is there a method through which I could cast the content as string and get the content ? Or should I rewrite the query to format the result as strings ?
You have a wrong understanding of types or at least this:
array(9) { [0]=> **string**(1) { ["column"]=> string(20) "..." } [1]=> **string**(1) { ["column"] ....
doesn't make any sense. You believe you want elements to be of type string but yet contain array data which really doesn't work.
What you actually want is a different array structure but you are heading in the wrong direction for that.
You basically have two options:
Modify the getAllUsers() method in a way that returns your data in a structure you actually need.
Modify the data after you have received it. Obviously there's no builtin function convert_data_to_how_i_want_them() - so a basic understanding of arrays is required.
Basically you create a new array and copy those values you need to the position you need them at.
Something like this should do the trick in this case:
$out = array();
foreach($in as => $value) {
$out[] = $value['column'];
}

PHP arrays. Read post data in dot notation

How can i read this data i'm getting on my page via post?
This are the variables as they appear on firebug under POST.
list[0].firstName =test 1
list[0].name =test
list[1].name =test
I know that php replaces dots with underscores so i can access something like "address.box" by doing:
$_POST[address_box];
but i really can't figure out how to access all the above data.
Seems like that php doesn't want to read whatever comes after the square brackets, overwriting all the fields with the same index (list[0].firstName seems to get overwritten by list[0].name .
Any solution?
EIDT:
Here a var_dump of the data:
address.number 1
list[0].firstName firstname0
list[0].name name0
list[1].name name1
array(2) { ["list"]=> array(2) { [0]=> string(10) "firstname0" [1]=> string(5) "name1" } ["address_number"]=> string(1) "1" }
No. This is not possible within the PHP-language.
You must use either $object->field or $array['key'] notation.

Categories