0

我正在尝试将 xml(网站)处理成 php 数组。

我已经尝试了以下代码,它适用于结果中的每一个,但我需要获取我无法看到如何做到这一点的总页数。

function get_content($url) 
    /// basically opens the page and stores it as a variable. Buggered if I know how it works! 
    {   
        $ch = curl_init();  
        curl_setopt ($ch, CURLOPT_URL, $url);
        curl_setopt ($ch, CURLOPT_HEADER, 0);
        ob_start();
        curl_exec ($ch);
        curl_close ($ch);
        $string = ob_get_contents();
        ob_end_clean();
        return $string;
        $string = NULL;
        $ch = NULL;
        $url = NULL;
    }
$url = "url";
$content = get_content($url);
$content_x = explode("<result>", $content);

foreach ($content_x as $item)
    {
        $p1 = strpos($item, '<title>');
        $p2 = strpos($item, '</title>');
        $l1 = $p2 - $p1;
        echo '<br>'.$title = substr($item, $p1, $l1);
    }

xml 网站提要

<?xml version="1.0" encoding="UTF-8"?>
<response version="2">

    <totalpage>1005</totalpage>

    <results> 
        <result>
            <title>test</title>
            <title2>test2</title2>
            <title3>test3</title3>
        <result>
                <result>
            <title>test</title>
            <title2>test2</title2>
            <title3>test3</title3>
        <result>
                <result>
            <title>test</title>
            <title2>test2</title2>
            <title3>test3</title3>
        <result>
                ........so on

    <results>

</response>

我需要得到总页数结果中的每一个

如何获得总页数,它们是处理结果的更好方法吗

4

1 回答 1

0

您绝对不应该使用字符串操作来尝试解析 XML。有许多 PHP 库可以做到这一点。我可能会推荐 SimpleXML。

用法是:

$xml = simplexml_load_string($content);
$totalpage = $xml->response->totalpage;
于 2013-01-11T22:40:31.670 回答