I have the following php code that I am looking to put into an array, and then json_encode:
$teamQuery = $xpath->query("//td[@align='left']");
$pointsQuery = $xpath->query("//td[@class='sortcell']");
$data = array ();
for($x=1; $x<=30; $x++){
$data[$x]['id'] = $teamQuery->item($x)->nodeValue;
$data[$x]['Team Points'] = $pointsQuery->item($x)->nodeValue;
}
echo json_encode($data);
The output looks like this:
{"1":{"id":"Team Query\n","Points Query":"110"},"
For the purposes of my project I would like to remove the line break (\n), as well as the leading {"1": in the code.
Any help and guidance would be greatly appreciated!
1 Answer 1
I would like to remove the line break (\n)
trim($teamQuery->item($x)->nodeValue)
as well as the leading {"1":
Then don't index your array starting from 1.
Put together:
$data = array();
for ($x = 1; $x <= 30; $x++) {
$data[] = array(
'id' => trim($teamQuery->item($x)->nodeValue),
'Team Points' => $pointsQuery->item($x)->nodeValue
);
}
answered Apr 2, 2014 at 13:04
Sign up to request clarification or add additional context in comments.
2 Comments
user3468600
This worked perfectly. Would you be able to advise as to how I could then echo json_encode($data); into a variable that will plot these values using javascript? I am currently able to do it in two steps: 1. Run the php separately and get the values array 2. take the values from the array and drop them into the javascript variable that is plotting them on a chart. I was hoping that dropping the echo json encode in the variable would work but it doesn't.
deceze
<script>var myValues = <?php echo json_encode($data); ?>;</script>lang-php
$data[$x])