PHP Simple XML Element Object - How to get string value - php

How do I get the values of the follow array fields in php? When I do a print_r function on a two dimensional array, I get the following result:
[title] => SimpleXMLElement Object ( ) [date] => SimpleXMLElement Object ( )
How do I get the string value of title and date? I've tried casting them with
(string)
, however this didn't work.

You need to access the attributes of the SimpleXMLElement Object.
Say you have an instance named entry with child title you type
(string) $entry->title;

Related

Nested Array Foreach Issue

I am very basic new php learner, i having difficulty to get nested array value, here is my json result:
stdClass Object
(
[title] => Aao Raja - Gabbar Is Back | Chitrangada Singh
[link] => stdClass Object
(
[22] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fmp4&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=145.542&itag=22&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1432539432699196&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=3547894526817B37774A7838F8B68493CDD62101.3F143C74D76E8705800445A4CD4476C4F8BCD988&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => hd720
)
[43] => Array
(
[0] => http://r8---sn-aigllnsk.c.docs.google.com/videoplayback?mime=video%2Fwebm&id=o-AExJcTxRDvCYsfgA1cIvQDs1v-pvLhKjTPdDh67X19vz&dur=0.000&itag=43&pl=48&ip=2a03:b0c0:1:d0::2f6:c001&sparams=dur,expire,id,ip,ipbits,itag,lmt,mime,mm,mn,ms,mv,nh,pl,ratebypass,source,upn&key=cms1&sver=3&expire=1437035009&upn=9lTw9Popb18&ratebypass=yes&source=youtube&lmt=1428933984759484&fexp=901816%2C9407809%2C9408142%2C9408420%2C9408710%2C9409172%2C9412774%2C9412846%2C9413149%2C9415664%2C9415958%2C9416126%2C9416370%2C9416656&ipbits=0&signature=266C126464ECDB4CC0FF076CD41F07BCC4DA7E34.08D9F13B7BF7D92FD1E1963336CC7FB8F19FE899&cms_redirect=yes&mm=31&mn=sn-aigllnsk&ms=au&mt=1437013301&mv=m&nh=IgpwcjAzLmxocjE0KgkxMjcuMC4wLjE&utmg=ytap1
[1] =>
[2] => medium
)
I can access the Title, but can't access the Link urls:
echo $title = $json->{'title'};
echo $link = $json->{'link'}->{'22'}->{'0'};
How can access the specific link array 22
This echo $title = $json->{'title'}; works because you are accessing an object's property and using -> is the correct way.
In this case $json->{'link'}->{'22'}->{'0'} you are trying to access an array item instead an object's property, because $json->{'link'}->{'22'} is an array and not an object. In this case, you should access it in this way: $json->{'link'}->{'22'}[0]. In order to avoid this kind of issues and, when you decode your JSON to a PHP object, you can pass true as a second parameter to the function json_decode and that will convert the whole object into an array. That way, you don't need to worry about accessing elements as object's attributes, you can access them, always, as array items. So, in this case, it would be: $json["link"]["22"][0].
You're confusing the way you access objects and arrays.
Getting the title is correct via $json->title, but the link should be $json->link->{'22'}[0] - a mixture of objects and arrays.
FYI the {'name'} notation is the same as name - only required when you are including variables in your object name e.g. {$someVar . 'name'}
I suppose you use json_decode() function. Do you know that you can get an array instead of StdClass Object? So, you can use.
<?php
$php_array = json_decode($json_string, true);

How to retrieve #attributes array value?

Can someone help me retrieve the value of the id from this array? Thanks
Array
(
[#attributes] => Array
(
[id] => 1
)
)
This is a SimpleXML element. The #attributes key is just how it's set internally. Don't try to access it via that key.
You can just simply get the attribute by doing:
$id = (string)$element['id'];
Note: The cast to a string is needed because SimpleXML gives you a SimpleXMLElement object when you access something.

XML array to comma separated list

I have an array list of tags from xml file and im using xml file to add some posts to wordpress. So i need to convert xml array to comma separated list for tags to import in my posts.
This is an xml file example
<tags>
<tag>tag1</tag>
<tag>tag2</tag>
<tag>tag3</tag>
</tags>
So when i call this file in my .php file and use print_r to get the output i get this
SimpleXMLElement Object (
[tag] => Array (
[0] => SimpleXMLElement Object ( )
[1] => SimpleXMLElement Object ( )
[2] => SimpleXMLElement Object ( )
[3] => SimpleXMLElement Object ( )
)
)
So 0 1 2 3 are tags and values are stored in SimpleXMLElement Object ( ) i read it's normal to not get values when using print_r but i know the values are there.
Now i need to convert this as a list at the end to get this result
$post_tags = tag1, tag2, tag3;
so that i can use $post_tags in my function.
Assuming your object (the one on which you called print_r() is $xml), you would loop over $xml->tag and append each child object's contents to an array. Finally, implode the array to a string.
// An array to hold it temporarily
$post_tags_arr = array();
foreach ($xml->tag as $t) {
// Cast it to a string to get the text value back
$post_tags_arr[] = (string)$t;
}
// Implode the array to a string
$post_tags = implode(', ', $post_tags_arr);
echo $post_tags;
You indicate that you need a list for $post_tags, but your syntax above is ambiguous as to whether you wanted a string or an array. If you wanted an array, you have it in $post_tags_arr prior to the implode().
If you feel like being clever, and the <tag> nodes reside at the same level and have no children, you can simply cast them as a regular array, which will result in their string values.
// Cast it to an array in one go:
$post_tags_arr = (array)$xml->tag;
print_r($post_tags_arr);
Array
(
[0] => tag1
[1] => tag2
[2] => tag3
)

Getting value from SimpleXMLElement Object

Hi I have this following segment of XML:
......
<Result number="4" position="1" points="25">
<Driver driverId="button" url="http://en.wikipedia.org/wiki/Jenson_Button">
<GivenName>Jenson</GivenName>
<FamilyName>Button</FamilyName>
<DateOfBirth>1980-01-19</DateOfBirth>
<Nationality>British</Nationality>
</Driver>
......
I can use the following easily to get the GivenName:
$item->Driver->GivenName;
But when I use:
$item->Driver->FamilyName;
I get SimpleXMLElement Object ()
I have looked around and found that it might be something to do with passing it to a string but then I get nothing on screen. Not even SimpleXMLElement Object.
I don't understand as it's a sibling of GivenName and that works.
You get a SimpleXMLElement object in both cases, which you'll see if you use print_r():
print_r ($item->Driver->GivenName);
print_r ($item->Driver->FamilyName);
Outputs:
SimpleXMLElement Object
(
[0] => Jenson
)
SimpleXMLElement Object
(
[0] => Button
)
You can use an explicit cast to get the values as strings:
$givenNameString = (string) $item->Driver->GivenName;
$familyNameString = (string) $item->Driver->FamilyName;
To make PHP understand you have to give typecasting forcefully on object like below:
$givenName = (array) $item->Driver->GivenName;
$familyName = (array) $item->Driver->FamilyName;
print_r($givenName);
print_r($familyName);
OUTPUT :
Array ([0] => 'Jenson')
Array ([0] => 'Button')

Extract data from an XML object

How do i extract the data from that xml object which is a value of a certain array:
Array ( [Title] => SimpleXMLElement Object (
[0] => The Key of Life; A Metaphysical Investigation )
[ASIN] => SimpleXMLElement Object ( [0] => 0982385099 ) ...
Do string typecasting of the object.
$variable = (string) $FieldValue[0];
That would work, as SimpleXml has all the children in object type and not string.
say $X is the object, so to print
The Key of Life; A Metaphysical
Investigation
you do:
echo $X->Title[0]
It's important to understand that you're not working with an array — you're working with a SimpleXMLElement object, which is not the same.
Instead of doing $array['key']['subkey'], you would do $xml->tag->subtag.
SimpleXML nodes are not strings or arrays, although they behave string-like and array-like. Make sure you always typecast the value to an explicit string.
If you're accessing the first node, you don't need to use [0]. It's assumed.
You can convert SimpleXMLElement objects into true associative arrays in PHP 5.2 or newer with:
$array = json_decode(json_encode($xml), true);

Categories