I'm using YouTube API. I got following result from API :
SimpleXMLElement Object
(
[#attributes] => Array
(
[rel] => alternate
[href] => http://www.youtube.com/watch?v=blabla
)
)
I'm confuse with this object. I want to access #attributes. How can i do it?
The #attributes part of the print_r output are just the element's attributes which can be accessed via $obj['attrname'].
<?php
$obj = new SimpleXMLElement('<foo rel="alternate" href="http://www.youtube.com/watch?v=blabla" />');
print_r($obj); // to verify that the sample data fits your actual data
echo $obj['rel'], ' | ', $obj['href'];
prints
SimpleXMLElement Object
(
[#attributes] => Array
(
[rel] => alternate
[href] => http://www.youtube.com/watch?v=blabla
)
)
alternate | http://www.youtube.com/watch?v=blabla
see also Example #5 Using attributes in the SimpleXML documentation.
Related
I have a RSS object $rssObject created using the PHP simplexml_load_file function, the goal is to get the value of [href].
var_dump($rssObject) returns the following:
Array
(
[0] => SimpleXMLElement Object
(
[link] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[href] => https://www.example.com
)
)
I have tried unsuccessfully to get the contents of [href] using this notation which returns null
$rssObject[0]->link[0]->{'#attributes'}['href'];
Not sure why?
Any help would be appreciated!
In SimpleXML, attributes are accessed using array notation:
$xml = simplexml_load_file();
$url = $xml[0]->link[0]['href'];
See "Example #5 Using attributes" in the PHP manual.
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!
As I have mentioned in question title, I am trying below code to reach till the desired node in xpath result.
<?php
$xpath = '//*[#id="topsection"]/div[3]/div[2]/div[1]/div/div[1]';
$html = new DOMDocument();
#$html->loadHTMLFile('http://www.flipkart.com/samsung-galaxy-ace-s5830/p/itmdfndpgz4nbuft');
$xml = simplexml_import_dom($html);
if (!$xml) {
echo 'Error while parsing the document';
exit;
}
$source = $xml->xpath($xpath);
echo "<pre>";
print_r($source);
?>
this is the source code. I am using to scrap price from a ecommerce.
it works it gives below output :
Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[class] => line
)
[div] => SimpleXMLElement Object
(
[#attributes] => Array
(
[class] => prices
[itemprop] => offers
[itemscope] =>
[itemtype] => http://schema.org/Offer
)
[span] => Rs. 10300
[div] => (Prices inclusive of taxes)
[meta] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[itemprop] => price
[content] => Rs. 10300
)
)
[1] => SimpleXMLElement Object
(
[#attributes] => Array
(
[itemprop] => priceCurrency
[content] => INR
)
)
)
)
)
)
Now How to reach till directly [content] => Rs. 10300.
I tried:
echo $source[0]['div']['meta']['#attributes']['content']
but it doesn't work.
Try echo (String) $source[0]->div->meta[0]['content'];.
Basically, when you see an element is an object, you can't access it like an array, you need to use object -> approach.
The print_r of a SimpleXMLElement does not show the real object structure. So you need to have some knowledge:
$source[0]->div->meta['content']
| | | `- attribute acccess
| | `- element access, defaults to the first one
| `- element access, defaults to the first one
|
standard array access to get
the first SimpleXMLElement of xpath()
operation
That example then is (with your address) the following (print_r again, Demo):
SimpleXMLElement Object
(
[0] => Rs. 10300
)
Cast it to string in case you want the text-value:
$rs = (string) $source[0]->div->meta['content'];
However you can already directly access that node with the xpath expression (if that is a single case).
Learn more on how to access a SimpleXMLElement in the Basic SimpleXML usage ExamplesDocs.
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.
When I print_r($var) I get the result below.
SimpleXMLElement Object
(
[SEND_FILE] => SimpleXMLElement Object
(
[FILEID] => 123
[GUID] => 456
[SUMMARY] => SimpleXMLElement Object
(
[NB_PAYMENTS] => 1
)
)
)
How can I get the value of the FILEID element in a variable? If I do
print $result->SEND_FILE->FILEID[0]
then I just get the number - what I want, no mention of a SimpleXML Object.
But if I put this variable in an array, as such
$res['file_id'] = $result->SEND_FILE->FILEID[0]
and then print_r($res) I get:
Array
(
[file_id] => SimpleXMLElement Object
(
[0] => 307466
)
)
How can I get it to remove the [0] / SimpleXMLElement Object?
This will look not too elegant, but try casting the result to integer (if the type is known):
$res['file_id'] = (int)$result->SEND_FILE->FILEID[0]
Why do you append the [0] at the end? You dont need that. You should simply do
print $result->SEND_FILE->FILEID;
And that should be enough.