Javascript 在单独的文件中与getJSON一起使用PHP数据时出现问题

Javascript 在单独的文件中与getJSON一起使用PHP数据时出现问题,javascript,php,jquery,ajax,getjson,Javascript,Php,Jquery,Ajax,Getjson,我在wos.php中创建了一个数组,然后我使用jQuery在另一个文件data.php中使用它json\u encode和echo。由于某种原因,数据未被提取 这是在wos.php中创建的数组($recordArray)的一个示例: Array ( [0] => Array ( [author1] => QIN, JUN-SHENG [citations] => 61

我在
wos.php
中创建了一个数组,然后我使用jQuery在另一个文件
data.php
中使用它
json\u encode
echo
。由于某种原因,数据未被提取

这是在
wos.php
中创建的数组(
$recordArray
)的一个示例:

Array
(
    [0] => Array
           (
               [author1] => QIN, JUN-SHENG
               [citations] => 61
           )
    [1] => Array
           (
               [author1] => KOHANE, DANIELS
               [citations] => 60
           )
    [2] ...etc...
这就是我执行
echo json\u encode($recordArray)
后数据的样子:

所有这些看起来都是正确的格式。然后在
data.php
中使用该数据,并使用jQuery/D3将其显示在条形图中。下面是该代码的一个片段,它应该使用
getJSON
wos.php
读取数据:

<!DOCTYPE HTML>

<html lang="en">

<head>
    <title>Academic Intelligence</title>
    ...etc...
</head>
<body>
    ...etc...
    <script type="text/javascript">

        // this is just so I know it has reached this point
        console.log("Works to here...");

        $(document).ready(function() {

            $.getJSON('wos.php', function(data) {

            alert(data);

            ...code that uses data to with D3 to display a bar graph...

            }
        }
    </script>
    ...etc...
</body>
</html>
"; // =================================================================== // //================创建变量以存储所需数据===============================// //=====================来自XML并显示在表中======================================================================// // =================================================================== // //创建一个数组来存储每次迭代每个记录的数据 $recordArray=array(); //创建一个数组来表示要忽略的引用值,即对引用少于4次的出版物不感兴趣 $ignore=数组(0,1,2,3,4); //遍历所有记录,搜索每100条记录并将数据制成表格 对于($i=1;$i数组)( 'databaseId'=>'WOS', 'userQuery'=>$queryType1.'='.$queryJournal1.$queryJournal2.$queryJournal3.'和'$queryType2.'='.$queryType1.$queryType2.$QueryType3, 'editions'=>array('collection'=>'WOS','edition'=>'SCI'), 'timeSpan'=>array('begin'=>$timeStart,'end'=>$timeEnd), “queryLanguage”=>“en” ), “retrieveParameters”=>数组( “计数”=>“100”, “sortField”=>数组( 数组('name'=>$sortType,'sort'=>'D') ), “firstRecord”=>$i ) ); //收集当前迭代的搜索响应 试一试{ $search\u response=$search\u client->search($search\u数组); }捕获(例外$e){ echo$e->getMessage(); }; //将Soap客户端对象从当前响应转换为SimpleXMLElement $xml=newsimplexmlement($search\u response->return->records); //保存变量名以供全局使用 $author1=“”; //$author2=“”; //$author3=“”; $cictions=“”; //迭代当前数据集,并将其制表到网页上,再加上存储在变量中 foreach($xml->REC as$record){ //第一作者 $author1=(字符串)$record->static\u data->summary->name->name[0]->全名; //第二作者 /*如果(isset($record->static_data->summary->names->name[1]->full_name)){ $author2=(字符串)$record->static\u data->summary->name->name[1]->全名; 回显“.$author2.”; }否则{ 回显“”。“无记录”; $author2=“无记录”; } //第三作者 如果(isset($record->static\u data->summary->names->name[2]->full\u name)){ $author3=(字符串)$record->static\u data->summary->name->name[2]->全名; 回显“.$author3.”; }否则{ 回显“”。“无记录”; $author3=“无记录”; } */ //引用数,如果为零,则完成填充数组,然后完全“中断”循环(对零引用记录不感兴趣) 如果(!在数组中($record->dynamic_data->citation_related->tc_list->silo_tc->attributes(),$ignore)){ $引文=(字符串)$record->dynamic_data->citation_related->tc_list->silo_tc->attributes(); }否则{ 破口2; }; //对于此迭代,映射记录到临时数组变量aRecord中的所有值(相当于表中的一行数据) $arecord=array(“author1”=>strtoupper($author1), //“author2”=>$author2, //“author3”=>$author3, “引文”=>$引文 ); //将此迭代中的数据传递到数组变量“$recordArray”,在所有迭代之后,$recordArray中的每个元素都将是单个日志的单个记录或数据行 array\u push($recordArray,$arecord); } }; //需要替换文本中的单引号以避免在插入mysql时转义,以及其他字符以帮助删除重复项 对于($i=0;$i检索到的数据:
”; “打印”

****附加的****

按要求提供
index.php
的完整代码:

<?php

// TIMING INITIALISE
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime; 


// set processing time for browser before timeout
ini_set('max_execution_time', 3600);
// override default PHP memory limit
ini_set('memory_limit', '-1');

// ensures anything dumped out will be caught, output buffer
ob_start();

// set WSDL for authentication and create new SOAP client
$auth_url  = "http://search.webofknowledge.com/esti/wokmws/ws/WOKMWSAuthenticate?wsdl";
// array options are temporary and used to track request & response data in printout below (line 65)
$auth_client = @new SoapClient($auth_url, array(
                 "trace" => 1,
                 "exceptions" => 0));
// run 'authenticate' method and store as variable
$auth_response = $auth_client->authenticate();

// set WSDL for search and create new SOAP client
$search_url = "http://search.webofknowledge.com/esti/wokmws/ws/WokSearch?wsdl";
// array options are temporary and used to track request & response data in printout below (line 130)
$search_client = @new SoapClient($search_url, array(
                 "trace" => 1,
                 "exceptions" => 0));
// call 'setCookie' method on '$search_client' storing SID (Session ID) as the response (value) given from the 'authenticate' method
$search_client->__setCookie('SID',$auth_response->return);


// =================================================================== //
// ============== PASS IN PARAMETERS FOR SOAP REQUEST ================ //
// =================================================================== //

// data passed in from user via form in index.html

// search type for journals (publication name)
$queryType1 = "SO";
// keyword(s)
$queryJournal1 = $_POST["journal1"];

// check if journal2 field has been populated, if not entered then set to blank
if (!$_POST["journal2"]) {
    $queryJournal2 = "";
} else {
    $queryJournal2 = $_POST["journal2"];
    $queryJournal2 = " OR " .$queryType1. "=" .$queryJournal2;
}

// check if journal3 field has been populated
if (!$_POST["journal3"]) {
    $queryJournal3 = "";
} else {
    $queryJournal3 = $_POST["journal3"];
    $queryJournal3 = " OR " .$queryType1. "=" .$queryJournal3;
}

// search type for titles
$queryType2 = "TI";
// keyword(s)
$queryTitle1 = $_POST["title1"];

// check if title2 field has been populated
if (!$_POST["title2"]) {
    $queryTitle2 = "";
} else {
    $queryTitle2 = $_POST["title2"];
    $queryTitle2 = " OR " .$queryType2. "=" .$queryTitle2;
}

// check if title3 field has been populated
if (!$_POST["title3"]) {
    $queryTitle3 = "";
} else {
    $queryTitle3 = $_POST["title3"];
    $queryTitle3 = " OR " .$queryType2. "=" .$queryTitle3;
}

// sort type
$sortType = "TC";

// check if timespan fields have been populated
if (!$_POST["timeStart"]) {
    $timeStart = "1864-01-01";
    $timeEnd = "2080-01-01";
} else {
    $timeStart = $_POST["timeStart"];
    $timeEnd = $_POST["timeEnd"];
}

// create an array to store all the search parameters to pass to data.html to display with the graph
$searchParams = array('journal1' => $queryJournal1,
                      'journal2' => $queryJournal2,
                      'journal3' => $queryJournal3,
                      'title1' => $queryTitle1,
                      'title2' => $queryTitle2,
                      'title3' => $queryTitle3,
                      'from' => $timeStart,
                      'to' => $timeEnd,
                     );

// turn top cited authors data into JSON file for displaying with JavaScript in data.html
// file_put_contents('search.json', json_encode($searchParams));

// pass in relevant parameters for search, this is the format necessary for Web of Science Web Service
$search_array = array(
    'queryParameters' => array(
        'databaseId' => 'WOS',
        'userQuery' => $queryType1.'='.$queryJournal1 . $queryJournal2 . $queryJournal3 . ' AND ' .$queryType2. '=' .$queryTitle1 . $queryTitle2 . $queryTitle3,
        'editions' => array('collection' => 'WOS', 'edition' => 'SCI'),
        'timeSpan' => array('begin' => $timeStart, 'end' => $timeEnd),
        'queryLanguage' => 'en'
    ),
    'retrieveParameters' => array(
        'count' => '100',
        'sortField' => array(
            array('name' => $sortType, 'sort' => 'D')
        ),
        'firstRecord' => '1'
    )
);


// =================================================================== //
// ======== PERFORM SEARCH USING PARAMETERS & SOAP CLIENT ============ //
// =================================================================== //


// try to store as a variable the 'search' method on the '$search_array' called on the SOAP client with associated SID 
try {
    $search_response = $search_client->search($search_array);
} catch (Exception $e) {  
    echo $e->getMessage(); 
};

// number of records found by search, used to finish loop
$len = $search_response->return->recordsFound;

echo "</br>RECORDS FOUND: </br>";
print "<pre>\n";
print $len;
print "</pre>";


// =================================================================== //
// ============ CREATE VARIABLES TO STORE REQUIRED DATA ============== //
// ================== FROM XML & DISPLAY IN TABLE ==================== //
// =================================================================== //


// create an array to store data for each record per iteration
$recordArray = array();
// create an array to represent citation values to ignore, i.e. not interested in any publications with less than 4 citations
$ignore = array(0, 1, 2, 3, 4);

// iterate through all records, perform search for each 100 records and tabulate data
for ($i = 1; $i <= $len; $i+=100) {

    // set search parameters for current iteration (first record = 1, 101, 201, 301 etc.)
    $search_array = array(
        'queryParameters' => array(
            'databaseId' => 'WOS',
            'userQuery' => $queryType1.'='.$queryJournal1 . $queryJournal2 . $queryJournal3 . ' AND ' .$queryType2. '=' .$queryTitle1 . $queryTitle2 . $queryTitle3,
            'editions' => array('collection' => 'WOS', 'edition' => 'SCI'),
            'timeSpan' => array('begin' => $timeStart, 'end' => $timeEnd),
            'queryLanguage' => 'en'
        ),
        'retrieveParameters' => array(
            'count' => '100',
            'sortField' => array(
                array('name' => $sortType, 'sort' => 'D')
            ),
            'firstRecord' => $i
        )
    );

    // gather search response for current iteration
    try {
        $search_response = $search_client->search($search_array);
    } catch (Exception $e) {  
        echo $e->getMessage(); 
    };

    // turn Soap Client object from current response into SimpleXMLElement
    $xml = new SimpleXMLElement($search_response->return->records);

    // save variable names for global use
    $author1 = "";
    // $author2 = "";
    // $author3 = "";
    $citations = "";

    // iterate through current data set and tabulate onto webpage plus store in variable
    foreach($xml->REC as $record) {
        // first author
        $author1 = (string)$record->static_data->summary->names->name[0]->full_name;
        // second author
        /* if (isset($record->static_data->summary->names->name[1]->full_name)) {
            $author2 = (string)$record->static_data->summary->names->name[1]->full_name;
            echo '<td>'.$author2.'</td>';
        } else {
            echo '<td>'."no record".'</td>';
            $author2 = "no record";
        }
        // third author
        if (isset($record->static_data->summary->names->name[2]->full_name)) {
            $author3 = (string)$record->static_data->summary->names->name[2]->full_name;
            echo '<td>'.$author3.'</td>';
        } else {
            echo '<td>'."no record".'</td>';
            $author3 = "no record";
        } */
        // number of citations, if zero then finish populating array then 'break' out of loop entirely (not interested in zero cited records)
        if (!in_array($record->dynamic_data->citation_related->tc_list->silo_tc->attributes(), $ignore)) {
            $citations = (string)$record->dynamic_data->citation_related->tc_list->silo_tc->attributes();
        } else {
            break 2;
        };

        // for this iteration map all the values recorded into a temporary array variable, aRecord (equivalent to one row of data in table)
        $arecord = array("author1"=>strtoupper($author1),
                         // "author2"=>$author2,
                         // "author3"=>$author3,
                         "citations"=>$citations
                        );

        // pass the data from this iteration into the array variable '$recordArray', after all iterations, each element in $recordArray will be a single record or row of data for a single journal
        array_push($recordArray, $arecord) ;
    }
};    

// need to replace single quotes in text to avoid escaping when inserting to mysql, and other charas to help remove duplicates
for ($i = 0; $i < count($recordArray); $i++) {
    $recordArray[$i]['author1'] = str_replace("'", " ", $recordArray[$i]['author1']);
    $recordArray[$i]['author1'] = str_replace(".", "", $recordArray[$i]['author1']);
    $recordArray[$i]['author1'] = str_replace(". ", "", $recordArray[$i]['author1']);
    $recordArray[$i]['author1'] = str_replace(" ", "", $recordArray[$i]['author1']);
    // $recordArray[$i]['author2'] = str_replace("'", " ", $recordArray[$i]['author2']);
    // $recordArray[$i]['author3'] = str_replace("'", " ", $recordArray[$i]['author3']);
}

echo "</br>RETRIEVED DATA: </br>";
print "<pre>\n";
print_r($recordArray);
print "</pre>";

// as length of $j loop will decrease each time because of 'unset' its elements, create a variable to dynamically store its length
$length = count($recordArray);
$count = 0;

// iterate each author in $recordArray, ignore last value otherwise would end up comparing it to itself in inner loop
for ($i = 0; $i < (count($recordArray) - 1); $i++) {
    // iterate each author in $recordArray a step ahead of the outer loop, compare each author with every other author in array
    for ($j = ($i + 1); $j < $length; $j++) {
        // if there is a match between author names then (@ignores undefined offset error occuring due to 'unset'):
        if ($recordArray[$i]['author1'] === $recordArray[$j]['author1']) {
            // add second citations value to first
            $recordArray[$i]['citations'] += $recordArray[$j]['citations'];
            // remove second instance
            unset($recordArray[$j]);
            // add to a variable the number of times 'unset' has been used for this iteration of $i
            $count++;
        }; // end if
    }; // end inner loop ($j)
    // decrease length of inner loop by $count, i.e. the number of elements that were removed in the last iteration, to make the length of the inner loop correct
    $length -= $count;
    // reset $count for next iteration of $i
    $count = 0;
    // reset indices
    $recordArray = array_values($recordArray);
}; // end outer loop ($i)

// sort array according to citation values
// make sure that data is sorted correctly (citations_sum, high -> low)
usort($recordArray, function ($a, $b) {
    return $b['citations'] - $a['citations'];
});

// only include first ten elements in array
$recordArray = array_slice($recordArray, 0, 10);

// make sure all the values are strings, when encoding the summed ints seem to cause problems
for ($i = 0; $i < (count($recordArray)); $i++) {
    $recordArray[$i]['citations'] = (string)$recordArray[$i]['citations'];
};

echo "</br>FINAL DATA: </br>";
print "<pre>\n";
print_r($recordArray);
print "</pre>";

// turn top cited authors data into JSON file for displaying with JavaScript
// file_put_contents('data.json', json_encode($recordArray));

// clear the output buffer
while (ob_get_status()) {
    ob_end_clean();
}

header("Location: data.php");
// include "data.php";

// output $recordArray in JSON format to be picked up by JavaScript in data.php
echo json_encode($recordArray);

// =================================================== //
// ================ TIMING END ======================= //
// =================================================== //


$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = ($endtime - $starttime);
echo "This page was created in ".$totaltime." seconds";

?>
PHP Parse error:  syntax error, unexpected '[', expecting ')'
$recordArray = Array(0 => Array("author1" => "QIN, JUN-SHENG","citations" => 61),1 => Array("author1" => "KOHANE, DANIELS","citations" => 60));


期刊名称
添加更多字段
关键词
添加更多字段
<!DOCTYPE HTML>
<head>
</head>

<body>
        <!-- main content -->
        <section class="container">
            <div class="row">
                <!-- search params -->
                <form action="wos.php" method="post" role="form" class="form-horizontal" id="form">
                    <fieldset>
                        <div class="form-group">
                            <div class="col-lg-6 well bs-component">

                                <div class="journal_fields_wrap">
                                    <!-- keyword(s) for journal name(s) -->
                                    <label>Journal Title</label>
                                    <a class="btn btn-success" id="journal_list" target="_blank" href="http://ip-science.thomsonreuters.com/cgi-bin/jrnlst/jlresults.cgi?PC=D">Journal List</a>
                                    <button class="add_journal_field_button btn btn-info" type="button">Add more fields</button>
                                    <div>
                                        <input class="form-control" type="text" name="journal1" data-toggle="tooltip"
                                               title="this is a tooltip">
                                    </div>
                                </div>

                                <div class="title_fields_wrap">
                                    <!-- keyword(s) for paper title(s) -->
                                    <label>Keyword</label>
                                    <button class="add_title_field_button btn btn-info" type="button">Add more fields</button>
                                    <div>
                                        <input class="form-control" type="text" name="title1" data-toggle="tooltip"
                                               title="">
                                    </div>
                                </div>

                                <!-- timespan -->
                                <label>TIMESPAN</label></br>
                                <label>From: <input class="form-control" type="date" name="timeStart" placeholder="YYYY-MM-DD"></label>
                                <label>To: <input class="form-control" type="date" name="timeEnd" placeholder="YYYY-MM-DD"></label><br/><br/>

                                <!-- execute search -->
                                <button type="submit" class="btn btn-primary btn-lg">Submit</button>

                            </div> <!-- col-lg-6 -->

                            <div class="col-lg-6 well bs-component">

                                <div class="jumbotron">
                                    <h1>How to..</h1>
                                    <p>Please enter only one journal title or keyword per box.</p>
                                    <p>If you would like further information on x, y and z, then please,
                                    <a class="btn btn-warning btn-lg" target="_blank" href="#">Click here</a></p>
                                </div>

                            </div> 

                        </div> <!-- form-group -->
                    </fieldset>
                </form>
            </div> <!-- row -->

            <!-- TEMPORARY PLACEMENT FOR LOADING BAR -->
            <div class="row">
                <div class="col-lg-6">
                    <h3 style="color:red">Temporary progress bar is Temporary</h3>
                    <div class="progress progress-striped active">
                        <div class="progress-bar" style="width: 40%"></div>
                    </div>
                </div>
                <div class="col-lg-6"></div>
            </div>

        </section> <!-- main content; container -->
    </div> <!-- sg-content -->

    <!-- FOOTER -->
    <div class="sg-clear">&nbsp;</div>
    <div class="sg-footer">
        <p>Research &amp; Enterprise Services<br/>Newcastle University, Newcastle Upon Tyne,<br/>NE1 7RU, United Kingdom<br/><a href="mailto:res.policy@ncl.ac.uk">Email Webmaster</a><br/><br/>&copy; 2014 Newcastle University</p>
    </div>

    <!-- SCRIPTS -->

    <!-- jquery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <!-- local script -->
    <script src="script.js"/></script>
    <!-- bootstrap js -->
    <script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
    <!-- angularJS -->
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
    <!-- check browser version, if outdates, prompt for update -->
    <script src="//browser-update.org/update.js"></script>

</body>
PHP Parse error:  syntax error, unexpected '[', expecting ')'
$recordArray = Array(0 => Array("author1" => "QIN, JUN-SHENG","citations" => 61),1 => Array("author1" => "KOHANE, DANIELS","citations" => 60));
include "data.php";
var data = $.parseJSON( '<?php echo json_encode($recordArray) ?>' );
alert(data);