Using cURL and simpleXMLElement to extract data. How do I get the value of the XML element after XPATH?

耗尽温柔 提交于 2019-12-11 16:33:08

问题


I am having some problems extracting the data I want from a SimpleXMLElement object. Here is the basics of the code I am using:

curl_setopt( $ch, CURLOPT_URL, $URL );
$html = curl_exec( $ch );
$html = $tidy->parseString( $html, $tc, 'utf8' );
$tidy->cleanRepair();
$html = $tidy->body()->value;
$xml = new SimpleXMLElement( $html );

$xml = $xml->xpath( "//ul[@id='wxoptions']/li[3]/a" ); //Your XPATH

print_r( $xml );

This navigates to the correct HTML element I want, but prints:

Array
(
    [0] => SimpleXMLElement Object
        (
            [@attributes] => Array
                (
                    [href] => http://www.mylink.com
                    [title] => mylink
                )

            [0] => mylink
        )

)

The value I need is the [href], "http://www.mylink.com" in that array. How do I extract that from the output I included? I'm stumped and very new to SimpleXMLElement and Xpath.


回答1:


Use iterate, and attributes

foreach ( $xml->xpath( "//ul[@id='wxoptions']/li[3]/a" ) as $node)
{
  $href = $node->attributes("href");
}

Or directly called :

$href = $xml[0]->attributes("href");


来源:https://stackoverflow.com/questions/8466567/using-curl-and-simplexmlelement-to-extract-data-how-do-i-get-the-value-of-the-x

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