I can't get content from simplexml - php

I'm beginning to use simplexml and I don't know what I'm doing wrong .. :(
I want to extract a xml from a url, I'm using the following code:
$xml = new SimpleXMLElement(file_get_contents($url));
And... print_r shows other object SimpleXML inside my array...It is correct? How can I read it?
SimpleXMLElement Object
(
[action] => QUERY
[response] => SUCCESS
[responsedata] => SimpleXMLElement Object
(
)
)
Thanks a lot,

SimpleXMLElement::__construct provides an optional (3rd) argument called data_is_url for cases like yours.
By default, data_is_url is FALSE. Use TRUE to specify that data is a path or URL to an XML document instead of string data.
You should try something like:
$xml = new SimpleXMLElement($url, 0, true);

Related

How do i get order notes using PHP with the woocommerce REST API json response

I'm trying to follow http://woocommerce.github.io/woocommerce-rest-api-docs/?php#list-all-order-notes to get order notes from my orders and get the author and id inside a nested json respons but it's not working
Does anything stand out as being wrong here?
require_once 'auth.php';
$notes = $woocommerce->get('orders/108668/notes');
$json = json_decode($notes, true);
foreach($json as $elem) {
echo($elem['id']. ", ".$elem['author'] );
echo("<br/>");
}
If i print_r($notes); I get the response like so
Array ( [0] => stdClass Object ( [id] => 24721 [author] => haspden [date_created] => 2020-12-07T09:03:01 [date_c........
if i print_r($json); i get nothing :/
Any thouhgts? I'm sure it something obvious and due to my missunderstanding between arrays and objects with json.
Thanks
Try casting $notes with array and expose it as json using json_encode:
$notes = $woocommerce->get('orders/108668/notes');
header('Content-Type: application/json'); // this line is to make sure the output format is JSON
echo json_encode((array)$notes);
As I understand from what you supplied, the response from $notes = $woocommerce->get('orders/108668/notes'); is already an array and you can loop through it and do whatever you like. You don't need to json_decode it.
Moreover, json_decode first parameter is string as the docs says but you supplied an array.

after json in php i get stdClass and cannot use array

i use JSON.stringify(pageSettings) in jquery to ajax an array to php and save the file. file content:
{"MidHeight":367,"BotTop":502}
i use json_decode to load it back to array in php:
$pageSettings=json_decode(file_get_contents($path.$file);
when i print_r($pageSettings,true) results are:
stdClass Object
(
[MidHeight] => 276
[BotTop] => 411
)
but when i try to read from it with:
$pageSettings["MidHeight"]
i get:
PHP Fatal error: Cannot use object of type stdClass as array.
Either use property-access notation ($pageSettings->MidHeight) or tell json_decode to always give you an associative array using the second argument: $pageSettings = json_decode($json_str, true);

PHP Array generated from Xpath Query - Trying to extract data

I am currently attempting to extract values from an array that was generated by an SIMPLEXML/XPATH Query. I have had no success with my attempts if anyone can take look would be greatly appreciated.
I am looking just to extract ReclaimDate. I have tried a few functions and some of the advice on this post with no luck.
Array
(
[0] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ReclaimDate] => 05/15/2008
[ReclaimPrice] => 555555555
[_Owner] => ownername
)
)
)
If I just had to take a stab, I'd agree that what #Frank Farmer said should work:
// if $myVar is what you print_r'ed
echo (string)$myVar[0][0]['ReclaimDate'];
or this
echo (string)$myVar[0][0]->attributes('ReclaimDate');
http://www.php.net/manual/en/simplexml.examples-basic.php#example-4587
This is resolved thanks to Frank Farmer and Dan Beam.
This worked : echo (string)$check_reo[0][0]['ReclaimDate']
For anyone that is looking to use SimpleXML and XPATH to extract and write some basic logic from an XML file this is what worked for me.
$xmlstring = <<<XML <?xml version='1.0' standalone='yes'?> <YOURXMLGOESHERE>TEST</YOURXMLGOESHERE> XML;
$xpathcount = simplexml_load_string($xmlstring); // Load XML for XPATH Node Counts
$doc = new DOMDocument(); // Create new DOM Instance for Parsing
$xpathcountstr = $xpathcount->asXML(); // Xpath Query
$doc->loadXML($xpathcountstr); // Load Query Results
$xpathquery = array($xpathcount->xpath("//XMLNODEA[1]/XMLNODEB/*[name()='KEYWORDTOCHECKIFXMLCEXISTS']"));
print_r ($xpathquery) // CHECK Array that is returned from the XPATH query
`Array
(
[0] => Array
(
[0] => SimpleXMLElement Object
(
[#attributes] => Array
(
[ReclaimDate] => 05/15/2008
[ReclaimPrice] => 555555555
[_Owner] => ownername
)
)
) // Array RETURNED`
echo (string)$xpathquery[0][0]['ReclaimDate'] // EXTRACT THE VALUE FROM THE ARRAY COLUMN;
This site helped me receive a better understanding on how XPATH can search XML very easily with a lot more features than what I had previously known.
http://zvon.org/xxl/XPathTutorial/Output/examples.html
Here is the simple XML Function that worked for me
$xmlread = simplexml_load_string($xmlstring, "simple_xml_extended");
`class simple_xml_extended extends SimpleXMLElement { // Read XML and get attribute
public function Attribute($name){
foreach($this->Attributes() as $key=>$val) {
if($key == $name)
return (string)$val;
}
}
}`
Here is the Function action when extracting Single Values with an attribute based XML results
$GETVAR1 = $xmlread->XMLNODE1->XMLNODE2->XMLNODE3->XMLNODE4->XMLNODE5[0]->Attribute('XMLNODE5ATTRIBUTE');
This might not be the most efficient or best method, but its what ended working our for me. Hope this helps someone out who is still unclear about SIMPLEXML and XPATH.
An additional link for further insight: http://www.phpfreaks.com/tutorial/handling-xml-data

Why am I getting an array of SimpleXMLElement Objects here?

I have some code that pulls HTML from an external source:
$doc = new DOMDocument();
#$doc->loadHTML($html);
$xml = #simplexml_import_dom($doc); // just to make xpath more simple
$images = $xml->xpath('//img');
$sources = array();
Then, if I add all of the sources with this code:
foreach ($images as $i) {
array_push($sources, $i['src']);
}
echo "<pre>";
print_r($sources);
die();
I get this result:
Array
(
[0] => SimpleXMLElement Object
(
[0] => /images/someimage.gif
)
[1] => SimpleXMLElement Object
(
[0] => /images/en/someother.jpg
)
....
)
But when I use this code:
foreach ($images as $i) {
$sources[] = (string)$i['src'];
}
I get this result (which is what is desired):
Array
(
[0] => /images/someimage.gif
[1] => /images/en/someother.jpg
...
)
What is causing this difference?
What is so different about array_push()?
Thanks,
EDIT: While I realize the answers match what I am asking (I've awarded), I more wanted to know why whether using array_push or other notation adds the SimpleXMLElement Object and not a string when both arent casted. I knew when explicitly casting to a string I'd get a string. See follow up question here:Why aren't these values being added to my array as strings?
The difference is not caused by array_push() -- but by the type-cast you are using in the second case.
In your first loop, you are using :
array_push($sources, $i['src']);
Which means you are adding SimpleXMLElement objects to your array.
While, in the second loop, you are using :
$sources[] = (string)$i['src'];
Which means (thanks to the cast to string), that you are adding strings to your array -- and not SimpleXMLElement objects anymore.
As a reference : relevant section of the manual : Type Casting.
Sorry, just noticed better answers above, but the regex itself is still valid.
Are you trying to get all images in HTML markup?
I know you are using PHP, but you can convert use this C# example of where to go:
List<string> links = new List<string>();
if (!string.IsNullOrEmpty(htmlSource))
{
string regexImgSrc = #"<img[^>]*?src\s*=\s*[""']?([^'"" >]+?)[ '""][^>]*?>";
MatchCollection matchesImgSrc = Regex.Matches(htmlSource, regexImgSrc, RegexOptions.IgnoreCase | RegexOptions.Singleline);
foreach (Match m in matchesImgSrc)
{
string href = m.Groups[1].Value;
links.Add(href);
}
}
In your first example, you should:
array_push($sources, (string) $i['src']);
Your second example gives an array of strings because you are converting the SimpleXMLElements to strings using the (string) cast. In your first example you are not, so you get an array of SimpleXMLElements instead.

How to access a member of an stdClass in PHP that starts with an #

I have some json object that I decoded, and one of the attributes starts with an "#" and I can't access the element with php because it throws an error.
[offers] => stdClass Object
(
[#attributes] => stdClass Object
(
[id] => levaka0B8a
)
)
How would I go about accessing attributes?
You can access it by a string:
echo $obj->{'#attributes'}->id; // levaka0B8a
Or a variable:
$name = '#attributes';
echo $obj->$name->id;
For more information on how variables are defined and used, see the following docs:
Variable Basics - Useful for learning what can be accessed as a variable without needing to use strings.
Variable Variables - How we used the variable to act as the name for another variable. This can be dangerous so tread carefully
You could do this:
$object->{'#attributes'}
Try to use,
$objSimpleXml->attributes()->id
Sample Code to Refer
<?php
$string = <<<XML
<a>
<foo name="one" game="lonely">1</foo>
</a>
XML;
$xml = simplexml_load_string($string);
var_dump( $xml );
foreach($xml->foo[0]->attributes() as $a => $b) {
echo $a,'="',$b,"\"\n";
}
?>
direct access is below from ircmaxwell or Richard Tuin, however you can decode JSON with second param true and recive array insted what could be an easier to access

Categories