Why aren't these values being added to my arra

2019-09-03 17:05发布

问题:

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.