Why aren't these values being added to my array as strings?

可紊 提交于 2019-12-12 01:58:30

问题


Further to my question here, I'm actually wondering why I'm not getting strings added to my array with the following code.

I get some HTML from an external source with this:

$doc = new DOMDocument();
@$doc->loadHTML($html);
$xml = @simplexml_import_dom($doc); // just to make xpath more simple
$images = $xml->xpath('//img');
$sources = array(); 

Here is the images array:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [alt] => techcrunch logo
                    [src] => http://s2.wp.com/wp-content/themes/vip/tctechcrunch/images/logos_small/techcrunch2.png?m=1265111136g
                )

        )
   ...
)

Then I added the sources to my array with:

foreach ($images as $i) {   
  array_push($sources, $i['src']);
} 

But when I print the results:

 echo "<pre>";
 print_r($sources);
 die();

I get this:

Array
(
    [0] => SimpleXMLElement Object
        (
            [0] => http://www.domain.com/someimages.jpg
        )
    ...
)

Why isn't $i['src'] treated as a string? Isn't the original [src] element noted where I print $images a string inside there?

To put it another way $images[0] is a SimpleXMLElement, I understand that. But why is the 'src' attribute of THAT object not being but into $sources as a string when I reference it as $i['src']?


回答1:


Why isn't $i['src'] treated as a string?

Becaue it isn't one - it's a SimpleXMLElement object that gets cast to a string if used in a string context, but it still remains a SimpleXMLElement at heart.

To make it a real string, force cast it:

array_push($sources, (string) $i['src']);  



回答2:


Because SimpleXMLElement::xpath() (quoting) :

Returns an array of SimpleXMLElement objects

and not an array of strings.


So, the items of your $images array are SimpleXMLElement objects, and not strings -- which is why you have to cast them to strings, if you want strings.



来源:https://stackoverflow.com/questions/5668561/why-arent-these-values-being-added-to-my-array-as-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!