开发者

Confused on how to read xml object returned by curl in php

开发者 https://www.devze.com 2023-02-05 03:43 出处:网络
This is my php code: <?php if (array_key_exists(\"site\", $_GET) && $_GET[\"site\"] != \"\" )

This is my php code:

<?php   
if (array_key_exists("site", $_GET) && $_GET["site"] != "" )
{ 
    $url = $_REQUEST['site'];
    $url = " http://api.mywot.com/0.4/public_query2?target=";   
    $result= $url.urlencode($url); 
    $process = curl_init($result); 
    //init curl connection
    curl_setopt($process, CURLOPT_HEADER, 0);    
    curl_setopt($process, CURLOPT_POST, 1); 
    curl_setopt($process, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($process,CURLOPT_CONNECTTIMEOUT,1);
    $resp = curl_exec($process); 
    curl_close($process); 
    header('Content-Type: text/xml');
    $xml = new SimpleXMLElement($resp);
}
?>

Assumed xml:

<?xml version="1.0" encoding="UTF-8"?>
 <query target="example.com">
   <application name="0" r="89" c="44"/>
   <application name="1" r="89" c="46"/>
   <application name="2" r="92" c="47"/>
   <application name="4" r="93" c="48"/>
 </query>

I know how to read this kind of xml file

<Status>
    <code>200</code>
    <request>geocode</request>
&l开发者_运维技巧t;/Status>

$status = (int) $xml->Status->code;

The above xml has repeated tags such as application, how can I read certain ones?


application items will be accessible as an array, example: $xml->application[3]

$x = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?>
 <query target="example.com">
   <application name="0" r="89" c="44"/>
   <application name="1" r="89" c="46"/>
   <application name="2" r="92" c="47"/>
   <application name="4" r="93" c="48"/>
 </query>');

 print_r($x); // View entire XML structure

 print_r($x->application[1]); // View the 2nd application item

 echo $x->application[1]['c']; // Get 'c' attribute from 2nd item (46)


$xml->application[0];

$xml->application[1];

$xml->application[2];

...


In addition to other answers you can also use XPath to get certain elements from an XML structure:

$xml->xpath('/query/application[@name=2]')

will return the <application> element with attribute name = 2. See w3schools XPath tutorial for more info on conditions. Just keep in mind that XPath is somewhat slow in PHP with SimpleXML, even though you won't notice it unless you have a large document with thousands of elements. It's a good way of seeking not-so-big XMl structures. If you have to deal with large sets you might want to switch to DOMDocument. It isn't as simple and easy to follow but it has much greater performance with XPath.

Update

I see you're trying to parse full response as XMl. But $resp will actually contain FULL response, I mean including headers. Of course it won't parse correctly. What you need to do is:

//...
$resp = curl_exec($process);
$resp = substr( $resp, curl_getinfo($process, CURLINFO_HEADER_SIZE) );
curl_close($process); 
//...
0

精彩评论

暂无评论...
验证码 换一张
取 消