如何修复致命错误:未捕获的错误:在字符串上调用成员函数children()

时间:2019-06-04 00:26:13

标签: php html xml

我收到错误致命错误:未捕获的错误:当我尝试解析xml网页并将数据写入mysql数据库表时,在字符串上调用成员函数children()

我试图通过使用以下代码来做到这一点 任何人都可以请我以正确的方式为我提供建议,以解析xml网页终结点并将数据写入mysql数据库表中

<?php
function sanitize_for_xml($input) {
    // Convert input to UTF-8.
    $old_setting = ini_set('mbstring.substitute_character', '"none"');
    $input = mb_convert_encoding($input, 'UTF-8', 'auto');
    ini_set('mbstring.substitute_character', $old_setting);

    // Use fast preg_replace. If failure, use slower chr => int => chr conversion.
    $output = preg_replace('/[^\x{0009}\x{000a}\x{000d}\x{0020}-\x{D7FF}\x{E000}-\x{FFFD}]+/u', '', $input);
    if (is_null($output)) {
        // Convert to ints.
        // Convert ints back into a string.
        $output = ords_to_utfstring(utfstring_to_ords($input), TRUE);
    }
    return $output;

}
?>
<?php

                        $affectedRow = 0;
                        $url ="https://ngcareers.com/xmlfeed.xml";
                        $xml = simplexml_load_file($url) or die("Error: Cannot create object");
                        $xml = sanitize_for_xml($xml);
                        echo "xml is ".$xml;

                        $xml = str_replace("[^\\x20-\\x7e]", "",$xml);
                        $xml = str_replace("<b>", "",$xml);
                        $xml = str_replace("<u>", "",$xml);
                        $xml = str_replace("</u>", "",$xml);
                        $xml = str_replace("<providerUrl>", "",$xml);
                        $xml = str_replace("</providerUrl>", "",$xml);
                        $xml = str_replace("&lsquo;", "",$xml);
                        $xml = str_replace("&amp;", "",$xml);
                        $xml = str_replace("&rsquo;", "",$xml);
                        $xml = str_replace("&bull;", "",$xml);
                        $xml = str_replace("<strong>", "",$xml);
                        $xml = str_replace("</strong>", "",$xml);
                        $xml = str_replace("<p>", "",$xml);
                        $xml = str_replace("</p>", "",$xml);
                        $xml = str_replace("<br />", "",$xml);
                        $xml = str_replace("</b>", "",$xml);
                        $xml = str_replace("<li>", "",$xml);
                        $xml = str_replace("</li>", "",$xml);
                        $xml = str_replace("<ul>", "",$xml);

                        $xml = str_replace("</ul>", "",$xml);
                        $xml = str_replace("&#39;", "",$xml);
                        $xml = str_replace("&nbsp;", "",$xml);
                        $xml = str_replace("&quot;", "",$xml);
                        $xml = str_replace("<!--[endif]-->", "",$xml);
                        $xml = str_replace("<!--[if !supportLists]-->;", "",$xml);

                        foreach ($xml->children() as $row) {
                            $title = $row->title;
                            $link = $row->url;
                            $description = $row->description;
                            $date = $row->date;
                            $city = $row->city;
                            $state = $row->state;
                            $country = $row->country;
                            $company = $row->company;
                            $requirements= $row->requirements;
                            $category = $row->category;
                            $experience = $row->experience;
                            $salary = $row->salary;
                            $id = $row->id;

                            $sql = "INSERT INTO requirement(title,link,description,
                            jobdate,city,state,
                            country,company,requirements,
                            category,experience,salary,jobid) VALUES ('" . $title . "','" . $link . "','" . $description .
                                "','" . $date .  "','" . $city . "','" . $state . "','" . $country . "','" . $company . "','" .
                                $requirements . "','" . $category . "','" . $experience . "','" . $salary . "','" . $id
                                . "')";

                            $result = mysqli_query($con, $sql);

                            if (! empty($result)) {
                                $affectedRow ++;
                            } else {
                                $error_message = mysqli_error($con) . "\n";
                            }
                        }
                        ?>
                        <h2>Insert Job Data to  Table </h2>
                        <?php
                        if ($affectedRow > 0) {
                            $message = $affectedRow . " records inserted";
                        } else {
                            $message = "No records inserted";
                        }

                        ?>

2 个答案:

答案 0 :(得分:0)

您最好将let gradientLayer = CAGradientLayer() gradientLayer.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: CGSize(width: self.imgView.frame.size.width, height: self.imgView.frame.size.height*0.3)) gradientLayer.colors = [UIColor.black.withAlphaComponent(0.7).cgColor, UIColor.clear.cgColor] self.imgView.layer.addSublayer(gradientLayer) let gradientLayer2 = CAGradientLayer() gradientLayer2.frame = CGRect(origin: CGPoint(x: 0, y: (self.imgView.frame.size.height-self.imgView.frame.size.height*0.3)), size: CGSize(width: self.imgView.frame.size.width, height: self.imgView.frame.size.height*0.3)) gradientLayer2.colors = [UIColor.clear.cgColor, UIColor.black.withAlphaComponent(0.7).cgColor] self.imgView.layer.addSublayer(gradientLayer2) 用于实际的数据库插入,而IMO,最好将标准prepared statementDOMDocument结合使用来查询XML feed。就处理DOM而言,以下方法有效,但尚未通过db insert进行测试

DOMXPath

更新的代码-愉快地插入99/100行

<?php
    /* utility to get item from XPath query relative to $obj */
    function nodevalue( $xp, $obj, $item ){
        return $xp->query($item,$obj)->item(0)->textContent ?: false;
    }


    $affectedRow = 0;
    $url='https://ngcareers.com/xmlfeed.xml';

    /* create DOMDodument - use our own error handling */
    libxml_use_internal_errors( true );
    $dom=new DOMDocument;
    $dom->validateOnParse=false;
    $dom->recover=true;
    $dom->load( $url );
    libxml_clear_errors();

    /* create the XPath object for queryng the DOM */
    $xp=new DOMXPath( $dom );

    /* Get a list of all jobs */
    $col=$xp->query( '//jobs/job' );




    if( $col->length > 0 ){
        /* create the basic SQL insert statement for use in a `prepared statement` */
        $sql='insert into `requirement`
            ( `title`, `link`, `description`, `jobdate`, `city`, `state`, `country`, `company`, `requirements`, `category`, `experience`, `salary`, `jobid` ) 
            values
            ( ?,?,?,?,?,?,?,?,?,?,?,?,? )';

        /* create the prepared statement */
        $stmt=$con->prepare( $sql );

        if( $stmt ){

            /* Bind the placeholders to variables */
            $stmt->bind_param('ssssssssssssi',
                        $title,
                        $link,
                        $description,
                        $date,
                        $city,
                        $state,
                        $country,
                        $company,
                        $requirements,
                        $category,
                        $experience,
                        $salary,
                        $id
                    );

            /* Iterate through all the jobs */
            foreach( $col as $job ){
                /* assign as variables each item from the job */
                $title=nodevalue( $xp, $job, 'title' );
                $link=nodevalue( $xp, $job, 'url' );
                $description=nodevalue( $xp, $job, 'description' );
                $date=nodevalue( $xp, $job, 'date' );
                $city=nodevalue( $xp, $job, 'city' );
                $state = nodevalue( $xp, $job, 'state' );
                $country = nodevalue( $xp, $job, 'country' );
                $company = nodevalue( $xp, $job, 'company' );
                $requirements= nodevalue( $xp, $job, 'requirements' );
                $category = nodevalue( $xp, $job, 'category' );
                $experience = nodevalue( $xp, $job, 'experience' );
                $salary = nodevalue( $xp, $job, 'salary' );
                $id = nodevalue( $xp, $job, 'id' );

                /* execute the INSERT statement */
                $status=$stmt->execute();

                if( $status )$affectedRow++;
            }


            echo $affectedRow==$col->length ? 'All records inserted' : sprintf('%d rows inserted',$affectedRow);

        }
    }
?>

答案 1 :(得分:0)

您在剥离xml标签后在xml上使用children()方法。这意味着您的xml现在实际上是一个字符串。您只能在xml上使用children()。

    $url ="https://ngcareers.com/xmlfeed.xml";
    $xml = simplexml_load_file($url);

    $data = [];

    foreach ($xml->children() as $key => $value) {
       if($value->getName() == 'jobs'){
          foreach ($value as  $jobValue) {
          $singleArr  =   [];
          foreach ($jobValue->children() as $childkey => $childValue) {
             $singleArr[$childkey]     =   (string)$childValue;
          }
          $data[]     =   $singleArr;
       }
    }
   }
   echo '<pre>';print_r($data);

尝试像这样循环以解析xml数据。